yield
Returns a value from a block inside a switch expression.
Available since: Java 14
Syntax
case X -> { …; yield value; }Examples
A branch with several statements returns its value with yield:
void main() {
int code = 404;
String message = switch (code) {
case 200 -> "OK";
case 404 -> {
String text = "Not Found";
yield code + " " + text;
}
default -> "Unknown";
};
IO.println(message);
}Output:
404 Not FoundNotes
A single-expression arrow branch does not need yield. In the colon form of a switch expression, every branch needs yield: case 1: yield "one";. You cannot use return inside a switch expression — it would exit the whole method.
See also
- switch — Picks a branch by value; as an expression it returns a result.
In the tutorial
- switch — The switch statement in Java: arrow labels, several values per case, switch expressions that return a value, yield and the classic form with break.