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.
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
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.
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
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
yieldin a switch statement or anywhere else is a compile error. - Not needed for single expressions:
case X -> value;already yieldsvalue. Useyieldonly in a braced block or with colon-style labels. - Every path must produce a value or throw. A block that can finish without
yieldis a compile error. - Not
return.returnwould leave the enclosing method and is not allowed inside a switch expression;yieldonly 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 adoublecontext is widened. - Qualified calls: write
Thread.yield()for the thread hint;yield(โฆ)alone does not compile. - Not related to generators. Unlike
yieldin Python or JavaScript, Java'syielddoes not suspend and resume a method.
Related
switch,return,default,breakandcontinue- Lessons: switch