A return statement causes the program control to transfer back to the caller of a method. Every method in Java is declared with a return type and it is mandatory for all java methods. A return type may be a primitive type like int, float, double, a reference type or void type(returns nothing).
There are a few important things to understand about returning the values
- The type of data returned by a method must be compatible with the return type specified by the method. For instance, if the return type of some method is boolean, we can not return an integer.
- The variable receiving the value returned by a method must also be compatible with the return type specified for the method.
- The parameters can be passed in a sequence and they must be accepted by the method in the same sequence.
Example1
public class ReturnTypeTest1 { public int add() { // without arguments int x = 30; int y = 70; int z = x+y; return z; } public static void main(String args[]) { ReturnTypeTest1 test = new ReturnTypeTest1(); int add = test.add(); System.out.println("The sum of x and y is: " + add); } }
Output
The sum of x and y is: 100
Example2
public class ReturnTypeTest2 { public int add(int x, int y) { // with arguments int z = x+y; return z; } public static void main(String args[]) { ReturnTypeTest2 test = new ReturnTypeTest2(); int add = test.add(10, 20); System.out.println("The sum of x and y is: " + add); } }
Output
The sum of x and y is: 30