A record pattern is a declarative language construct that enables the automatic deconstruction of a record instance into its constituent components during pattern matching. Finalized in Java 21 (JEP 440), it extendsDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
instanceof operators and switch expressions/statements by binding a record’s internal state directly to local pattern variables, eliminating the need for explicit casting and accessor method invocations.
Syntax Structure
A record pattern consists of a record class type followed by a parenthesized list of pattern variables (or nested patterns) that correspond positionally to the record’s components.Deconstruction with instanceof
When a target object matches the specified record type, the JVM automatically invokes the record’s component accessors and initializes the declared pattern variables. These variables are scoped to the block where the pattern match is true.
Deconstruction in switch
Record patterns integrate directly into switch expressions and statements, allowing for exhaustive type-checking and component extraction across multiple branches.
Nested Record Patterns
Record patterns can be nested to deconstruct complex, hierarchical object graphs in a single operation. The outer pattern matches the primary record, while inner patterns recursively match and extract components of nested records.Type Inference with var
To reduce verbosity, the compiler can infer the types of the pattern variables based on the record’s canonical constructor signature. You can substitute explicit component types with the var identifier.
Nullability Mechanics
Target Object Nullability When evaluating a record pattern, the behavior with anull target object depends on the context:
instanceof: If the target object isnull, the pattern match evaluates tofalsegracefully without throwing aNullPointerException.switch: If the switch selector object isnull, theswitchstatement or expression will throw aNullPointerExceptionunless an explicitcase nullis provided.
null, the success of the match depends entirely on how the component patterns are declared:
varPatterns: If the component pattern usesvar, the match succeeds, and the corresponding pattern variable is assignednull.- Explicit Type and Nested Record Patterns: If the component pattern specifies an explicit type (e.g.,
Point p) or a nested record pattern (e.g.,Point(int x, int y)), it acts as an implicitinstanceofcheck. Becausenullis not an instance of any type, the match fails.
Master Java with Deep Grasping Methodology!Learn More





