A type pattern is a language construct in Java that combines type checking and conditional extraction into a single operation. It consists of a predicate that tests whether a target object matches a specific type and, upon a successful match, automatically casts and binds the target to a newly declared local variable, known as a pattern variable.Documentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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.
Master Java with Deep Grasping Methodology!Learn More





