Java and Spring Level 1 This level · 51 of 105
Easy java java-21

What is pattern matching for instanceof?

The 30 second answer

Since Java 16, instanceof can test the type and bind a variable in one step, so I don't need a separate cast afterwards. For example, if obj is a String s, I can use s directly. The variable only exists where the compiler knows the match succeeded, so it also works after an and condition, or after an early return when the check fails.

Could you say this in an interview?
// Before
if (obj instanceof String) { String s = (String) obj; use(s); }

// Java 16+
if (obj instanceof String s && !s.isEmpty()) { use(s); }

if (!(obj instanceof Order o)) return;
process(o);                         // o is in scope here (flow scoping)

The binding is in scope only where the match definitely succeeded; obj instanceof String s || s.isEmpty() doesn't compile. It also makes equals shorter:

public boolean equals(Object o) {
    return o instanceof Point p && x == p.x && y == p.y;
}

Previewed in Java 14 and 15, final in Java 16. Java 21 extends patterns to switch and to record deconstruction.

Sources (2)
  1. JEP 394: Pattern Matching for instanceofopenjdk.org
  2. JLS 6.3.1 Scope for Pattern Variablesdocs.oracle.com
Previous
Next