Part 14 / Topic 4 of 7
Record patterns (JEP 440)
A record pattern pulls a record's components apart directly inside instanceof or switch, instead of matching the whole record and then calling its accessors one by one. Record patterns nest, so a record holding another record can be deconstructed in a single pattern, several levels deep.
Think of asking for a parcel's full address in one go — city, pincode, state — rather than being handed one sealed envelope at a time and opening each yourself.
record Pincode(String code, String state) {}
record Address(String city, Pincode pincode) {}
record Customer(String name, Address address) {}
static String shippingLabel(Object maybeCustomer) {
if (maybeCustomer instanceof Customer(String name, Address(String city, Pincode(String code, var state)))) {
return name + ", " + city + " - " + code + " (" + state + ")";
}
return "not a customer record";
}
Three levels — Customer, its Address, that address's Pincode — deconstructed in one pattern, naming only the fields actually used (var works inside a record pattern too, same inference rules as a local variable).
Record patterns combine naturally with switch over a sealed hierarchy of records (section 3's exhaustiveness, with each case's fields pulled apart):
sealed interface Shape permits Circle, Rectangle {}
record Circle(double radiusCm) implements Shape {}
record Rectangle(double widthCm, double heightCm) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle(double r) -> Math.PI * r * r;
case Rectangle(double w, double h) -> w * h;
};
}
$ javac RecordPatternsDemo.java
$ java RecordPatternsDemo
-- nested record pattern deconstruction --
Asha Kulkarni, Pune - 411001 (Maharashtra)
Ravi Shah, Ahmedabad - 380001 (Gujarat)
not a customer record
-- record patterns in a switch, over a sealed Shape --
area: 28.27 cm2
area: 20.00 cm2
-- var inside a record pattern --
411001 is in Maharashtra (city: Pune)
🔍 Going deeper: section 3's
case Confirmed c -> c.coach()and section 4'scase Circle(double r) -> ...are two styles of the same thing — a type pattern binds the whole value; a record pattern additionally deconstructs it. Use whichever reads clearer for that case; mixing both styles in the sameswitch, as this part does across sections 3 and 4, is completely normal.
Full program: examples/RecordPatternsDemo.java.
Done here? The practice set for Part 14 — including the solutions — is on the part page.