J.VII · Java 25 practice question
What does the following Java 25 `switch` expression with pattern matching print?
void main() {
Object obj = "Java25";
String res = switch (obj) {
case Integer i -> "int:" + i;
case String s -> "str:" + s.length();
default -> "other";
};
System.out.println(res);
}
Check answer and explanation
Correct answer: str:6
Explanation
The selector `obj` matches the `String s` pattern, and `"Java25".length()` is `6`, printing `str:6`.
Common trap
`obj` is a `String`, not an `Integer`, and matches `case String s` before reaching `default`.
Source: JEP 441: Pattern Matching for switch — Summary
Checked against the cited text on 2026-11-27.