Return statement in Java

return is another reserved keyword in Java. It is almost always used along with methods. It is used to return a value from any method. It can also be used in methods that don’t return anything.

It can be used for two purposes

  • To return a value from a method.
  • To terminate the control flow inside a method.
1.1 To return a value from the method

return is the only way to return any value from a method that has a return type other than void.  In this case, the return-type of a method and data-type of the value returned by the return statement must match.

Output :

 


1.2  To terminate the control flow inside a method

return can be used in a method that returns nothing i.e the return type of the method is void. The syntax is :

In this case, the return keyword is used alone. It is not follwed by any object.

Sometimes, after some computation work of the method is done and you need not execute rest of the statements inside the method. In those situations, you can use return statement to return from the method call.

Output :

 


2. Return can be used to return any type including object type.

The return keyword can return an object of both primitive and reference type. In fact, it can return any type of data from a method.

Output :

 


3. If used, it must be the last statement in any code block.

A method can have any number of branches. If return is used in those branches, it must be the last statement to execute.

Output :

 


Summary

  • return-type of a method and data-type of the value returned by the return statement must match.
  • You can use return to exit the method call at any point, even if the return type is void. In this case blank return is used like return;.