J.VII · Java 25 practice question
What happens when a developer compiles this Java 25 program?
void main() {
Object obj = "hello";
switch (obj) {
case CharSequence cs -> System.out.println(cs.length());
case String s -> System.out.println(s);
default -> System.out.println("other");
}
}
Check answer and explanation
Correct answer: It fails to compile because the CharSequence pattern dominates the unreachable String pattern
Explanation
It fails to compile because the CharSequence pattern dominates the unreachable String pattern; every String is a CharSequence, so the String case label could never be selected.
Common trap
Developers may think switch simply picks the first matching branch or automatically prioritizes the most specific subtype like overloaded methods, but Java's pattern switch rejects dominated case labels at compile time.
Source: JEP 441: Pattern Matching for switch — Description
Checked against the cited text on 2026-11-25.