Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Returning a value from method

We can return a value of any type from a method, back to caller method.
For that, we must declare a suitable return type in the method header.
If a method does not return any value then its return type must be void.
A method gets terminate at the line where return keyword is used.
If return keyword is not used in the method, the code is executed until the end of the method.

Note

Type of the value returned by a method should match with the return type declared at method header.
The type of the variable receiving the returned value should also match with the return type of method.

Example

public class ReturnValue 
{
    public int addition(int a,int b) 
    {
        int sum = a+b;
        return sum;
    }
	
    public static void main(String args[]) 
    {
        ReturnValue r = new ReturnValue();
        int answer;
        answer = r.addition(10,20);
        System.out.println("Addition = "+answer);
    }
}

Output

Addition = 30

For a better understanding of the above program look at the diagram shown below:

Java Programming Language return Statement Working

The value of int variable sum is returned from addition() method to main() method (caller method).
It is then assigned to the int variable answer.

We can also use the expression with a return statement.

Example

public class ReturnValue2 
{
    public int addition(int a,int b) 
    {
        return (a+b);
    }
	
    public static void main(String args[]) 
    {
        ReturnValue2 r = new ReturnValue2();
        int answer;
        answer = r.addition(10,20);
        System.out.println("Addition = "+answer);
    }
}

Output

Addition = 30

 

Leave a reply