4.13 The return Statement
The return statement is used to stop execution of a method (or a constructor) and transfer control back to the calling code (also called the caller or invoker). The usage of the two forms of the return statement is dictated by whether that statement is used in a void or a non-void method (Table 4.2). The first form does not return any value to the calling code, but the second form does. Note that the keyword void does not represent any type.
In Table 4.2, the expression must evaluate to a primitive value or a reference value, and its type must be assignable to the return type specified in the method header (§2.7, p. 54, and §5.9, p. 261). See also the discussion on covariant return in connection with method overriding in §5.1, p. 201.
As can be seen from Table 4.2, a void method need not have a return statement—in which case the control typically returns to the caller after the last statement in the method body has been executed. However, a void method can specify only the first form of the return statement. This form of the return statement can also be used in constructors, as they likewise do not return a value.
Table 4.2 also shows that the first form of the return statement is not allowed in a non-void method. The second form of the return statement is mandatory in a non-void method, if the method execution is not terminated programmatically—for example, by throwing an exception. Example 4.14 illustrates the use of the return statement summarized in Table 4.2. A recommended best practice is to document the value returned by a method in a Javadoc comment using the @return tag.
Table 4.2 The return Statement
Form of return statement | In void method or in constructor | In non-void method |
return; | Optional | Not allowed |
return expression; | Not allowed | Mandatory, if the method is not terminated explicitly |
Example 4.14 The return Statement
public class ReturnDemo {
public static void main (String[] args) { // (1) void method can use return.
if (args.length == 0) return;
output(checkValue(args.length));
}
static void output(int value) { // (2) void method need not use return.
System.out.println(value);
return ‘a’; // Not OK. Cannot return a value.
}
static int checkValue(int i) { // (3) Non-void method: Any return statement
// must return a value.
if (i > 3)
return i; // OK.
else
return 2.0; // Not OK. double not assignable to int.
}
static int absentMinded() { // (4) Non-void method.
throw new RuntimeException(); // OK: No return statement provided, but
// method terminates by throwing an exception.
}
}