J.VII · Java 25 practice question

What happens when a developer compiles this Java 25 program?

void main() {
    Object obj = 'a';
    switch (obj) {
        case Character c:
            System.out.println(c);
        case Integer i:
            System.out.println(i);
            break;
        default:
            break;
    }
}
Choose one answer
Check answer and explanation

Correct answer: It fails to compile because execution cannot fall through a case label that declares a pattern variable

Explanation

It fails to compile because execution cannot fall through a case label that declares a pattern variable, as i would not be initialized if obj were a Character.

Common trap

Traditional colon switch cases allow fall-through, which makes expecting it to compile and print null or throw NullPointerException tempting, but the compiler rejects fall-through into any case label that declares a pattern variable.

Source: JEP 441: Pattern Matching for switch — Description
Checked against the cited text on 2026-11-25.

Report an error in this question