J.VII · Java 25 practice question

What happens when a developer tries to compile this Java 25 switch?

void main() {
    Object obj = 5;
    switch (obj) {
        case Character c, Integer i -> System.out.println("char or int");
        default -> System.out.println("other");
    }
}
Choose one answer
Check answer and explanation

Correct answer: It fails to compile because multiple patterns cannot be combined in a single comma-separated case label

Explanation

It fails to compile because multiple patterns cannot be combined in a single comma-separated case label, since one of the pattern variables would remain uninitialized.

Common trap

Arrow switch rules allow comma-separated constant labels like case 1, 2 ->, which makes expecting case Character c, Integer i -> to compile tempting, but multiple patterns in one case label are prohibited. A syntax/compile error prevents the program from running to print other.

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

Report an error in this question