• Returning a value

    Returning a value means storing the evaluated variable and return its data to the method it was called. The data type that should be return should be the same that was defined when creating the method. For example:

    package com.javapointers.javacore;
    
    public class Return {
    
         public int addNum(int a, int b){
              int answer = a + b;
              return answer;
         }
    
         public static void main(String args[]){
              Return ret = new Return();
              int ans = ret.addNum(10, 20);
              System.out.println(ans);
         }
    }

    In our example above, we have created a class named Return. Upon calling our main method, we have initialized our class. In the second line of the main method, we have called our method addNum(). Inside our addNum method was the adding of the variable a and b and save the answer to the variable answer and eventually return whatever the variable answer hold. This will result to 10 + 20 which is equal to 30 that will be hold by our variable answer. When we return the answer, it will go again to the method where it was called, ret.addNum(10, 20), and save the returning value to the variable ans. Giving us an output of 30.

    Related Post