Return Statement in Java
What is a return statement in Java?
In Java programming, the return statement is used for returning a value when the execution of the block is completed. The return statement inside a loop will cause the loop to break and further statements will be ignored by the compiler.
Returning a Value from a Method
In Java, every method is declared with a return type such as int, float, double, string, etc.
These return types required a return statement at the end of the method. A return keyword is used for returning the resulted value.
The void return type doesn't require any return statement. If we try to return a value from a void method, the compiler shows an error.
Following are the important points must remember while returning a value:
The syntax of a return statement is the return keyword is followed by the value to be returned.
The following Java programs demonstrate the use of return statements.
x = 3 y = 8 The greater number among x and y is: 8
In the above Java code, the method CompareNum is defined with the int return type. It compares the x and y values and returns the greater number.
x = 15 y = 24 The greater number among x and y is: 24
In the above Java code, the method CompareNum is defined with int return type and two arguments x and y. The method compares x and y values and returns the greater number.
Returning a Class or Interface
A method can have the class name as its return type. Therefore it must return the object of the exact class or its subclass.
An interface name can also be used as a return type but the returned object must implement methods of that interface.
The following Java program shows the implementation of a class name as a return type.
Additon result: 150
In the above code, a SumResult class contains an addition method with class name as its return type. It returns the result value and prints it using the display method.