J.VII · Java 25 practice question
What is the output when this Java 25 program is compiled and executed?
void main() {
Object obj = "hi";
switch (obj) {
case String s -> System.out.println("string:" + s);
case CharSequence cs -> System.out.println("seq:" + cs.length());
default -> System.out.println("other");
}
}
Check answer and explanation
Correct answer: string:hi
Explanation
The program prints string:hi because placing the more specific String pattern before CharSequence avoids dominance, and the first matching case label is selected.
Common trap
Printing seq:2 would only happen if the CharSequence branch ran instead of String, which does not occur since String appears first. Overlapping types are allowed in switch as long as the subtype pattern precedes the supertype pattern.
Source: JEP 441: Pattern Matching for switch — Description
Checked against the cited text on 2026-11-25.