Syntax
A type pattern consists of a type name followed by a variable declaration:Mechanics in instanceof
Introduced in Java 16, type patterns eliminate the need for explicit casting after an instanceof check. If the runtime type of the target object is assignment-compatible with the TargetType, the pattern matches, and the patternVariable is initialized with the casted value.
Mechanics in switch
Standardized in Java 21, type patterns can be used as case labels within switch statements and expressions. This allows a switch block to route execution based on the runtime type of the selector expression.
Flow Scoping
Pattern variables utilize flow scoping (or flow-sensitive typing). The scope of a pattern variable is strictly limited to the execution paths where the compiler can definitively prove that the pattern has matched. Short-circuit evaluation:Guarded Patterns
Type patterns inswitch blocks can be refined using the when keyword to apply additional boolean conditions, known as guards. The pattern variable is in scope within the when clause.
Nullability Rules
instanceof: A type pattern will never match anullreference. Ifobjisnull,obj instanceof String sevaluates tofalse, andsis not initialized.switch: A type patterncase String swill not match anullselector expression. To handlenullin a pattern-matching switch, an explicitcase nullmust be provided, or it can be combined with a type pattern usingcase null, String s.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More





