CKTIS / Java
return — exit from a method or lambda
return — exit from a method or lambda: return ends execution of the current method, constructor, or lambda body and optionally supplies a value to the caller.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
returnreturn ends execution of the current method, constructor, or lambda body and optionally supplies a value to the caller.
In a non-void method return an expression compatible with the result type; in a void method, constructor, or void lambda use bare return for early exit.
A finally block runs before the transfer completes, and its own return or throw can replace the original result or exception.
A value-returning method must not be able to complete normally: control may reach return, throw, or never complete, so an infinite loop is legal; return is forbidden in an initializer.
Three return paths classify -1, 0, and 2 as negative, zero, and positive respectively.
Examples
public class Main {
static String classify(int value) {
if (value < 0) return "negative";
if (value == 0) return "zero";
return "positive";
}
public static void main(String[] args) {
System.out.println(classify(-1));
System.out.println(classify(0));
System.out.println(classify(2));
}
}
Result
negative zero positive
Three return paths classify -1, 0, and 2 as negative, zero, and positive respectively.