Java / Java 21 Coding Standards Interview Questions
What is the purpose of pattern matching for instanceof in Java 21?
Pattern matching for instanceof combines the type check and the cast into a single expression: if the check succeeds, the compiler automatically binds the value to a new, correctly typed variable in the surrounding scope.
if (obj instanceof String s && !s.isBlank()) { System.out.println(s.trim()); }
Its purpose under coding standards is to eliminate the redundant explicit cast that traditionally followed an instanceof check, such as String s = (String) obj;, which was both boilerplate and a place where a copy-paste mistake could cast to the wrong type.
The pattern variable's scope is flow-sensitive: it is only definitely assigned in the branches where the compiler can prove the check succeeded, for example inside the if body above, or after a negated check followed by an early return.
More Related questions...