J.VII · Java 25 practice question

What does the following Java 25 program print when using a guarded pattern in a `switch` expression?

void main() {
    Object v = "hi";
    String res = switch (v) {
        case String s when s.length() > 3 -> "long";
        case String s -> "short";
        default -> "other";
    };
    System.out.println(res);
}
Choose one answer
Check answer and explanation

Correct answer: short

Explanation

`"hi".length()` is `2`, so the guard `s.length() > 3` is `false` and execution falls to the unguarded `case String s`, printing `short`.

Common trap

`long` requires a length greater than 3, and `default` is not reached because the second `String` pattern matches.

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

Report an error in this question