Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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 Found

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.