Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Keywords and Statements

The yield statement

Reference for Java yield: how a block in a switch expression produces its value, yield versus return, old-style case labels, and yield as a contextual keyword.

yield produces the result of a switch expression from inside a block. When a branch needs several statements before it can compute its value, you wrap them in braces and finish with yield value;. It was added in Java 14.

yield is a contextual keyword, not a fully reserved word. You can still use it as a name for variables or fields, but you cannot call a method named yield without qualifying it (Thread.yield()), because an unqualified yield(x); is parsed as the statement.

Java
int result = switch (kind) {
    case A -> 1;                 // plain expression: no yield
    case B -> {
        int tmp = compute();
        yield tmp * 2;           // block: yield the value
    }
    default -> 0;
};

Try it

Java yield in an arrow block

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 yield with old-style case labels

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
yield expression;
Part Description
expression Its value becomes the value of the whole switch expression. Its type must be compatible with the other branches.

Usage notes

  • Only inside a switch expression. A yield in a switch statement or anywhere else is a compile error.
  • Not needed for single expressions: case X -> value; already yields value. Use yield only in a braced block or with colon-style labels.
  • Every path must produce a value or throw. A block that can finish without yield is a compile error.
  • Not return. return would leave the enclosing method and is not allowed inside a switch expression; yield only leaves the switch.
  • Throwing is fine: a branch can be case X -> throw new ...; and needs no value.
  • Type of the expression: the result type is derived from all branches (a standalone switch) or from the assignment target, so yield 1; in a double context is widened.
  • Qualified calls: write Thread.yield() for the thread hint; yield(โ€ฆ) alone does not compile.
  • Not related to generators. Unlike yield in Python or JavaScript, Java's yield does not suspend and resume a method.