J.VII · Java 25 practice question

What is the result of compiling this Java 25 switch expression?

void main() {
    int n = 2;
    int res = switch (n) {
        case 1:
            yield 10;
        default:
            System.out.println("default");
    };
    System.out.println(res);
}
Choose one answer
Check answer and explanation

Correct answer: It fails to compile because the last statement in the switch block can complete normally

Explanation

It fails to compile because the last statement in the switch block can complete normally without a yield statement or throw, which is a compile-time error in a switch expression.

Common trap

Unlike local variables or fields with default values, a switch expression cannot implicitly return 0 when a colon group reaches the end. This defect is caught at compile time rather than throwing IllegalStateException at run time.

Source: JLS SE 25 §15.28.1. The Switch Block of a switch Expression
Checked against the cited text on 2026-11-25.

Report an error in this question