Pattern Matching for instanceof

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Pattern Matching for instanceof (finalized in Java 16) eliminates the need for explicit casting after type checking.
  • It combines the instanceof check and the cast into a single, clean expression.
  • It significantly reduces boilerplate and the risk of ClassCastException.

Concept

For over 20 years, Java developers wrote the classic “Check and Cast” idiom:

if (animal instanceof Dog) {
    Dog d = (Dog) animal;
    d.bark();
}

This is annoying. You say Dog three times in two lines. Furthermore, if you accidentally copy-paste and write Cat c = (Cat) animal inside the Dog block, the code will crash at runtime.

Pattern Matching for instanceof introduces a “Pattern Variable”. You provide the type you want to check against (Dog), and the name of a new variable (d). If the check passes, the compiler automatically casts the object and assigns it to d.

Examples

public class InstanceOfDemo {
    
    public void feedAnimal(Object obj) {
        
        // The old, clunky way
        if (obj instanceof Cat) {
            Cat cat = (Cat) obj;
            cat.meow();
        }
        
        // The modern Java 16 way
        if (obj instanceof Dog dog) {
            dog.bark();
        }
    }
    
    // Combining with logic
    public boolean isValidUser(Object obj) {
        // The pattern variable 'user' is immediately usable in the && clause!
        return (obj instanceof User user) && user.isActive();
    }
    
    // Advanced Scoping (Flow Scoping)
    public void printLength(Object obj) {
        // If it's NOT a String, we exit.
        if (!(obj instanceof String s)) {
            return;
        }
        // Because of the early return above, the compiler absolutely guarantees 
        // that if we reach this line, 'obj' is a String. 
        // Therefore, 's' is in scope here!
        System.out.println(s.toUpperCase());
    }
}

Interview Questions

Q: Can the pattern variable shadow a class field?
A: Yes, and it is a common source of confusion. If your class has a field private String name;, and you write if (obj instanceof String name), the pattern variable name will shadow (hide) the class field inside the if block. Modifying name will only modify the local pattern variable, not the class field.

Q: Does instanceof handle null values safely?
A: Yes! In both the old and new styles, null instanceof AnyClass always evaluates to false. If you pass a null object to if (obj instanceof Dog d), the condition will just silently fail and skip the block. It will never throw a NullPointerException.