Why this matters
- The test-then-cast pair appears in almost every
equalsmethod 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
switchand to record deconstruction.
Before and after
Loading compiler…
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 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.
Loading compiler…
Loading compiler…
Loading compiler…
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.