What is pattern matching for instanceof in Java 16?

Pattern matching for instanceof combines the type check and the cast into one step. If the check succeeds, the object is already cast and bound to a new variable, so you don't write a separate cast.

Key Points: • Old style: if (obj instanceof String) { String s = (String) obj; ... }. • New style: if (obj instanceof String s) { ... } where s is already a String. • The pattern variable is in scope only where the check is known to be true, including after && in the same condition. • It removes repetitive casts and the risk of casting to the wrong type. • It works well in equals() methods: return o instanceof Point p && p.x == x && p.y == y;.

Code Example:

public class InstanceofPatternDemo {

    static String describe(Object obj) {
        if (obj instanceof String s && !s.isBlank()) {
            return "String of length " + s.length();
        } else if (obj instanceof Integer i) {
            return "Integer, doubled = " + (i * 2);
        } else if (obj instanceof int[] arr) {
            return "int array with " + arr.length + " elements";
        }
        return "Something else [" + obj + "]";
    }

    public static void main(String[] args) {
        System.out.println(describe("Java"));
        System.out.println(describe(21));
        System.out.println(describe(new int[]{1, 2, 3}));
        System.out.println(describe(" "));
    }
}

Output:

String of length 4 Integer, doubled = 42 int array with 3 elements Something else [ ]

Good to Know: Mention that with || the variable is not in scope, because the check might be false: if (obj instanceof String s || s.isEmpty()) does not compile. Knowing the scoping rule shows you have actually used the feature.

Interview Tip: A concise interview answer is:

"Pattern matching for instanceof combines the type check and the cast: if (obj instanceof String s) gives me s already typed as a String. The variable is only in scope where the check is known to be true, which removes repetitive casts."

Previous question: What are switch expressions in Java, and how are they different from the old switch statement?

Next question: What is pattern matching for switch in Java 21?

More Java 17 and 21 Features interview questions

All Java 17 and 21 Features questions