JVM Knowledge

A yield statement transfers control by causing an enclosing switch expression (§15.28) to produce a specified value.

YieldStatement:
  yield Expression ;

A yield statement attempts to transfer control to the innermost enclosing switch expression; this enclosing expression, which is called the yield target, then immediately completes normally and the value of the Expression becomes the value of the switch expression.

It is a compile-time error if a yield statement has no yield target.

It is a compile-time error if the yield target contains any method, constructor, instance initializer, static initializer, or lambda expression that encloses the yield statement. That is, there are no non-local jumps.

It is a compile-time error if the Expression of a yield statement is void (§15.1).

Execution of a yield statement first evaluates the Expression. If the evaluation of the Expression completes abruptly for some reason, then the yield statement completes abruptly for that reason. If evaluation of the Expression completes normally, producing a value V, then the yield statement completes abruptly, the reason being a yield with value V.

It can be seen, then, that a yield statement always completes abruptly.

Example 14.21-1. The yield Statement

In the following example, a yield statement is used to produce a value for the enclosing switch expression.

class Test {
    enum Day {
        MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
        SATURDAY, SUNDAY
    }

    public int calculate(Day d) {
        return switch (d) {
            case SATURDAY, SUNDAY -> d.ordinal();
            default -> {
                int len = d.toString().length();
                yield len*len;
            }
        };
    }
}