Java / Java 21 Interview Questions
How does pattern matching for instanceof work in Java 16+?
JEP 394 (finalised in Java 16) extends the instanceof operator with a type pattern that both tests the type and binds a typed local variable in a single expression, eliminating the explicit cast that always followed a traditional instanceof check.
// Traditional — test + cast (redundant, error-prone)
if (obj instanceof String) {
String s = (String) obj; // redundant cast
System.out.println(s.length());
}
// Pattern matching instanceof (Java 16+)
if (obj instanceof String s) {
System.out.println(s.length()); // s is String, no cast needed
}
// The pattern variable is in scope only where the test is true
if (!(obj instanceof String s)) {
return; // s is NOT in scope here (obj didn't match)
}
// s IS in scope here — guard pattern
System.out.println(s.toUpperCase());
// Combine with &&
if (obj instanceof String s && s.length() > 3) {
System.out.println(s.trim()); // s in scope because && is short-circuit
}
// In equals() — cleaner implementation
@Override
public boolean equals(Object o) {
return o instanceof Point p
&& this.x == p.x
&& this.y == p.y;
}The scoping rule is precise: the pattern variable is in scope in the part of the expression where the type test is guaranteed to have been true. It is not in scope in the else branch or on the false side of ||. This is called flow scoping and the compiler enforces it statically.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
