Java

Pattern Matching for instanceof (Java 16+)

admin by @admin ADMIN
Jun 20, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Combine `instanceof` with a variable binding — no separate cast needed. Eliminates the most common "check then cast" bug pattern and is significantly less verbose.
Java
Raw
// Old way (pre-Java 16)
void process(Object o) {
    if (o instanceof String) {
        String s = (String) o;            // separate cast
        System.out.println(s.toUpperCase());
    }
}

// New way (Java 16+)
void process2(Object o) {
    if (o instanceof String s) {          // binding pattern
        System.out.println(s.toUpperCase());
    }
}

// Combined with && — s is in scope on the right
void process3(Object o) {
    if (o instanceof String s && s.length() > 5) {
        System.out.println("long string: " + s);
    }
}

// Record deconstruction (Java 21+)
record Point(int x, int y) {}
void describe(Object o) {
    if (o instanceof Point(int x, int y)) {
        System.out.printf("x=%d y=%d%n", x, y);
    }
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.