In Java, the return statement is used to exit a method and optionally return a value to the caller of that method. The return statement is most commonly used within methods to indicate the result of the method’s execution. Here’s the syntax for the return statement:
return [expression];
Code language: JavaScript (javascript)
[expression] is an optional value that the method can return to the caller. If the method is declared with a return type other than void, the return statement must provide an expression of that return type.
Let’s look at some examples of how the return statement works:
Example 1: Using return in a method without a return value (void method)
public class ReturnExample1 { public static void main(String[] args) { printHello(); } public static void printHello() { System.out.println("Hello, world!"); // No return value (void method) return; } }
In this example:
- The printHello method is declared as a void method, which means it doesn’t return any value.
- Inside the printHello method, we use the return; statement to exit the method. Although it doesn’t return a value, the return; statement is optional in void methods.
Example 2: Using return in a method with a return value
public class ReturnExample2 { public static void main(String[] args) { int result = add(5, 3); System.out.println("Result: " + result); } public static int add(int a, int b) { int sum = a + b; // Return the sum as the result of the method return sum; } }
In this example:
- The add method is declared with a return type of int, indicating that it will return an integer value.
- Inside the add method, we calculate the sum of two integers, a and b, and then use the return statement to return the sum as the result of the method.
- In the main method, we call add(5, 3) and store the returned value in the result variable, which is then printed.
Example 3: Using return to exit a method early
public class ReturnExample3 { public static void main(String[] args) { int result = divide(10, 0); System.out.println("Result: " + result); } public static int divide(int dividend, int divisor) { if (divisor == 0) { System.out.println("Division by zero is not allowed."); // Exit the method early and return a default value (0) return 0; } int quotient = dividend / divisor; return quotient; } }