Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

yield — producing a value from a switch expression

The yield statement supplies a value to the nearest enclosing switch expression. It is useful in a block arm that executes several statements before producing its result. In Java SE 21, yield is a contextual keyword.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

yield Expression;

In Java SE 21, yield is a contextual keyword, not a word reserved in every context. The statement yield Expression; evaluates Expression and supplies its value as the result of the nearest enclosing switch expression. It does not exit the method as return does.

The arm case 3 -> { ... } uses a block to perform calculations before supplying its result with yield. The arm default -> 0; supplies its result directly and needs no yield. A block arm of a switch expression cannot simply reach its end without a value; it can also complete by throwing an exception. break is not a replacement for yield when supplying a result.

Using yield without an enclosing switch expression, or with a void expression, is a compile-time error. It cannot jump from a nested lambda or method to an outer switch expression.

In the example, number is 3, so doubled is 6, and yield doubled + 1; makes the switch result 7. The example targets Java SE 21; the production runtime is not attested.

Examples

public class YieldExample {
    public static void main(String[] args) {
        int number = 3;
        int result = switch (number) {
            case 3 -> {
                int doubled = number * 2;
                yield doubled + 1;
            }
            default -> 0;
        };
        System.out.println(result);
    }
}

Result

7

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources