return
Ends a method and gives a value back to the caller.
Available since: Java 1.0
Syntax
return value;Examples
Returning a value and an early exit:
String grade(int score) {
if (score < 0) {
return "invalid";
}
return score >= 50 ? "pass" : "fail";
}
void main() {
IO.println(grade(75));
IO.println(grade(-1));
}Output:
pass
invalidNotes
A method with a result type must return a value on every path, otherwise you get "missing return statement". In a void method return; without a value exits early.
See also
- break / continue — break exits a loop, continue jumps to the next iteration; a label lets you leave a nested loop.
- yield — Returns a value from a block inside a switch expression.
Related recipes
In the tutorial
- Parameters and return values — Method parameters in Java, the result type, the return statement and passing arguments by value.