Skip to content
Tutorials Center
My learning

Topics

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.

Java
int square(int n) {
    return n * n;
}

void log(String s) {
    if (s == null) return;
    System.out.println(s);
}

Try it

Java Returning values and exiting early

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.

Java Conversions, finally and lambdas

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

Java
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 List or a small class.
  • Conversions apply: the expression is converted like an assignment, so return 5; in a long method is fine, but return 5L; in an int method is a compile error.
  • return inside try: the finally block runs before the method actually returns. A return inside finally overrides 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 long if/else pyramids.
  • Constructors may contain return; but never a value.
  • Unreachable code: a statement after return in the same block is a compile error.
  • main can use return; to end the program early, but only System.exit(n) sets the process exit code.
  • Covariant returns: an overriding method may return a subtype of the overridden method's return type.