Skip to main content
PreparationZone Logo
PrepZone

Pattern Matching for instanceof

Test, cast and bind in one step — and the guarded patterns that remove nested conditionals.

Pass checkpoint below

Read these first

Why this matters

  • The test-then-cast pair appears in almost every equals method and every piece of code handling a heterogeneous input, and it was always redundant.
  • The scoping rules for the bound variable are precise and occasionally surprising, which makes them a reliable interview question.
  • This is the first step of a larger feature: the same pattern syntax extends to switch and to record deconstruction.

Before and after

Java
Loading compiler…
Java
Loading compiler…
Before Java 16
1. instanceof check
2. Explicit cast
3. Assign to a variable
Java 16 and later
o instanceof String sTest, cast and bind in one step

s is in scope only where the test passed.

The type test and the binding happen together, so the variable is already the right type inside the branch and there is no cast left to get wrong.

The variable text is the pattern variable. It exists only where the pattern is known to have matched, and the compiler enforces that.

Where the pattern variable is in scope

This is the part worth reading carefully.

Java
Loading compiler…
Java
Loading compiler…
Java
Loading compiler…
Java
Loading compiler…

That guard-clause shape is the single biggest readability win in practice, because it removes a level of nesting from every method that validates its input.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 5 sections

  • Guarded patterns
  • equals, rewritten
  • Combining with sealed types
  • Keeping it readable
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.