return Statement in Java
The return statement is used to exit from a method and optionally return a value to the calling code.
It is commonly used in methods to send a result back to the caller.
Use Cases:
- To exit from a method immediately.
- To return a computed value from a method.
- Can be used in void methods (without value) or with return types like int, String, etc.
Example 1: Returning a value from a method
class ShikshaSanchar {
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = sum(5, 3);
System.out.println("Sum is: " + result);
}
}
Output:
Sum is: 8
Explanation:
- The sum() method takes two integers and returns their sum.
- The return statement sends the result back to main() where it is printed.
Example 2: Using return in a void method
class ShikshaSanchar {
public static void greet(String name) {
if (name == null) {
System.out.println("Name is missing.");
return; // exit early
}
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
greet(null);
greet("Simran");
}
}
Output:
Name is missing.
Hello, Simran
Explanation:
- When name is null, return exits the method early.
- For valid input, it continues and prints the greeting.
Example 3: return inside conditional logic
class ShikshaSanchar {
public static boolean isEven(int num) {
if (num % 2 == 0) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
System.out.println(isEven(4)); // true
System.out.println(isEven(7)); // false
}
}
Output:
true
false
Explanation:
- Based on condition, method returns either true or false.
- Caller receives the result and prints it.
Notes:
- A method with void return type cannot return a value — just return; to exit.
- Methods with a return type (int, String, etc.) must return a value.
- As soon as the return statement runs, the method stops right there — any code written after it will not be executed.
Summary:
- The return statement is used to exit from a method.
- It may return a value to the calling method.
- Works in both void and non-void methods.
- It is essential in methods that compute and return results.