J.VII · Java 25 practice question

What happens when a developer compiles this Java 25 code?

void main() {
    String text = "42";
    if (text instanceof Integer n) {
        System.out.println(n);
    }
}
Choose one answer
Check answer and explanation

Correct answer: It fails to compile because the Integer type pattern is not applicable at type String

Explanation

It fails to compile because the Integer type pattern is not applicable at type String; no testing conversion exists between the unrelated final reference types String and Integer.

Common trap

Testing an Object reference against Integer compiles and evaluates to false for a String, which makes thinking it prints nothing tempting, but static type String cannot be converted to Integer. instanceof never throws ClassCastException.

Source: JLS SE 25 §14.30.3. Properties of Patterns
Checked against the cited text on 2026-11-25.

Report an error in this question