Java Reference ยท Keywords and Statements
The return statement
Reference for Java return: returning values and void, early exits, return types and conversions, return in constructors, lambdas and try-finally.
return ends the execution of the current method, constructor or lambda body and hands control back to the caller. In a method with a non-void return type it must supply a value that is assignable to the declared type.
In a void method, constructor or initializer, return; leaves early without a value. This is the standard way to write guard clauses that keep the main logic flat.
int square(int n) { return n * n; } void log(String s) { if (s == null) return; System.out.println(s); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
return; // void methods, constructors, initializers return expression; // methods with a return type
| Context | Rule |
|---|---|
| Method with return type | Every path must end in return value; or throw, otherwise the compiler reports "missing return statement". |
void method / constructor |
Only return; is allowed. |
| Lambda body | return value; inside braces; an expression lambda needs no return. |
| Switch expression | You cannot return out of it; use yield for its value. |
Usage notes
- Only one value can be returned. To return several, use a record, an array, a
Listor a small class. - Conversions apply: the expression is converted like an assignment, so
return 5;in alongmethod is fine, butreturn 5L;in anintmethod is a compile error. returninsidetry: thefinallyblock runs before the method actually returns. Areturninsidefinallyoverrides any earlier return value or exception and is almost always a bug.- Return values are copies of references: returning an object returns its reference, not a clone, so callers can mutate returned internal collections. Return unmodifiable views or copies from classes that must protect state.
- Guard clauses (
if (bad) return;) reduce nesting compared with longif/elsepyramids. - Constructors may contain
return;but never a value. - Unreachable code: a statement after
returnin the same block is a compile error. maincan usereturn;to end the program early, but onlySystem.exit(n)sets the process exit code.- Covariant returns: an overriding method may return a subtype of the overridden method's return type.