Record patterns and deconstruction
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)You receive a Point record and only need its x and y. Calling a getter for each one before every use is slow to write and read.
Java 21: case Point(int x, int y) ->
A record pattern matches a record and takes out its components in one step, as in case Point(int x, int y).
A record is built from its components: new Point(3, 4). A record pattern does the reverse. Point(int x, int y) checks that the value is a Point, then calls its accessors x() and y() and puts the results into new variables x and y.
Example 1 · Deconstruct a Point in switch and in instanceof
// Java 21record Point(int x, int y) { }
public class PointPatternDemo { static String quadrant(Object o) { return switch (o) { case Point(int x, int y) when x == 0 && y == 0 -> "origin"; case Point(int x, int y) when x > 0 && y > 0 -> "quadrant 1"; case Point(int x, int y) when x < 0 && y > 0 -> "quadrant 2"; case Point(int x, int y) -> "other area (" + x + ", " + y + ")"; default -> "not a point"; }; }
public static void main(String[] args) { Object[] values = {new Point(0, 0), new Point(3, 4), new Point(-2, 5), new Point(1, -1), "3,4"}; for (Object v : values) { System.out.println(v + " -> " + quadrant(v)); }
Object stop = new Point(3, 4); if (stop instanceof Point(int x, int y)) { System.out.println("Distance squared from (0, 0): " + (x * x + y * y)); } }}Point[x=0, y=0] -> origin Point[x=3, y=4] -> quadrant 1 Point[x=-2, y=5] -> quadrant 2 Point[x=1, y=-1] -> other area (1, -1) 3,4 -> not a point Distance squared from (0, 0): 25
What this code does
Point(int x, int y)checks the type and pulls out both components, so the guards and bodies usexandywith nop.x()calls.- The same pattern works after
instanceof. Inside theif,xandyare in scope, just like a type pattern's variable.
Example 2 · Mistake: the pattern does not match the record's components
// Java 21record Point(int x, int y) { }
public class WrongComponentsDemo { static int sum(Object o) { if (o instanceof Point(int x)) { return x; } return 0; }
public static void main(String[] args) { System.out.println(sum(new Point(1, 2))); }}WrongComponentsDemo.java:6: error: incorrect number of nested patterns
if (o instanceof Point(int x)) {
^
required: int,int
found: int
1 errorWhat this code does
Pointhas two components, so a record pattern for it needs two nested patterns. You cannot skip one, even if you do not need it.- Write
Point(int x, int y)and simply ignorey, or usevar y. Also keep the component order of the record:Point(int y, int x)would silently swap the values.
With a type pattern you would write case Point p -> p.x() * p.x() + p.y() * p.y(). With a record pattern the same case is case Point(int x, int y) -> x * x + y * y. The data you need is named right in the case label, so the body reads like a formula. The pattern must list every component, in the record's order, with matching types. The names are yours to choose: Point(int a, int b) works too. Only the order and types matter.
Trace the code
Trace a record pattern
Variables
None yet.
Output
(nothing printed yet)Line 13main calls where with the record Point(0, 0).
Nested record patterns: an order with an address
A component can itself be a record, and then its pattern can be a record pattern too.
Example 3 · Nested patterns: an order with an address
// Java 21import java.util.List;
record Address(String city, int pin) { }
record Order(String id, Address to, int amount) { }
public class NestedOrderDemo { static String deliveryNote(Order order) { return switch (order) { case Order(String id, Address(String city, int pin), int amount) when city.equals("Pune") && amount >= 999 -> id + ": same-day delivery in Pune, free"; case Order(String id, Address(String city, int pin), int amount) when pin / 100000 == 1 -> id + ": North zone (" + city + "), Rs 60"; case Order(String id, Address(String city, int pin), int amount) -> id + ": standard to " + city + ", Rs 40"; case Order(String id, Address to, int amount) -> id + ": address missing, call customer"; }; }
public static void main(String[] args) { List<Order> orders = List.of( new Order("OD-1", new Address("Pune", 411001), 1499), new Order("OD-2", new Address("Delhi", 110001), 450), new Order("OD-3", new Address("Chennai", 600001), 799), new Order("OD-4", null, 299)); for (Order o : orders) { System.out.println(deliveryNote(o)); } }}OD-1: same-day delivery in Pune, free OD-2: North zone (Delhi), Rs 60 OD-3: standard to Chennai, Rs 40 OD-4: address missing, call customer
What this code does
Order(String id, Address(String city, int pin), int amount)reaches two levels deep, so the guard can usecityandamounttogether. Indian PIN codes starting with 1 belong to the Delhi region.OD-4has anulladdress. A nested record pattern never matchesnull, so the first three cases fail, and the last case with a plainAddress totype pattern catches it. That last case also makes the switch complete.
For record Order(String id, Address to, int amount) and record Address(String city, int pin), the pattern Order(String id, Address(String city, int pin), int amount) reaches two levels deep in one line.
You can mix levels freely: use a nested pattern where you need the inner pieces, and a type pattern such as Address a where you do not. A nested pattern can also carry a when guard that uses any of its variables: when city.equals("Pune") && amount > 999.
One rule about null: a nested record pattern never matches null. If an order's address is null, Order(var id, Address(var city, var pin), var amount) does not match, and the switch moves on. A plain type pattern for a component, such as String id, does accept a null id.
var inside record patterns
Writing every component type can make long patterns hard to read. Inside a record pattern you may write var instead of the type: case Order(var id, Address(var city, var pin), var amount).
Example 4 · var inside record patterns
// Java 21import java.util.List;
record Address(String city, int pin) { }
record Order(String id, Address to, int amount) { }
public class VarPatternDemo { public static void main(String[] args) { List<Order> orders = List.of( new Order("OD-7", new Address("Jaipur", 302001), 640), new Order("OD-8", new Address("Kochi", 682001), 1200));
int total = 0; for (Order o : orders) { if (o instanceof Order(var id, Address(var city, var pin), var amount)) { total += amount; System.out.println(id + " to " + city + " (" + pin + "): Rs " + amount); } } System.out.println("Total: Rs " + total); }}OD-7 to Jaipur (302001): Rs 640 OD-8 to Kochi (682001): Rs 1200 Total: Rs 1840
What this code does
varlets Java take each type from the record:idandcityareString,pinandamountareint. That is whytotal += amountworks as plain number addition.- The pattern is used with
instanceofhere, since every element has the same shape. The shape of the pattern still mirrors the shape of the data.
Java fills in each type from the record's definition, so amount is still an int.
Use var when the types are obvious from the record name. Write the type when it helps the reader, for example when a component is a long amount in paise rather than an int in rupees. The var: local type inference lesson covers var in general.
Record patterns with instanceof
Record patterns also work after instanceof: if (obj instanceof Point(int x, int y)). The test passes only if obj is a Point, and then x and y are in scope, following the same scope rules as other pattern variables.
// Java 21record Payment(String upiId, int amount) {}
public class BigPayment { public static void main(String[] args) { Object obj = new Payment("asha@upi", 750); if (obj instanceof Payment(String id, int amount) && amount > 500) { System.out.println(id + " paid Rs. " + amount); } Object other = "not a payment"; System.out.println(other instanceof Payment(String id, int amount)); }}asha@upi paid Rs. 750 false
Use the instanceof form when you check for one shape only. Use switch when there are several shapes to handle, especially for a sealed type where the compiler can check that every shape is covered.
if (o instanceof Point(int x, int y)) { ... }one shape, inside anif.if (o instanceof Order(var id, Address(var city, var pin), var amt) && amt > 500)switch (shape) { case Circle(double r) -> ...; case Rect(double w, double h) -> ...; }- Every component must appear; the variable names are your choice.
Real-world use: a small expression tree
Calculators, spreadsheet formulas and search filters are stored as trees. 2 + 3 × 4 becomes Add(Num(2), Mul(Num(3), Num(4))). A sealed interface Expr with records Num, Add, Mul and Neg describes every possible node.
Example 5 · Evaluating a small expression tree
// Java 21sealed interface Expr permits Num, Add, Mul, Neg { }
record Num(int value) implements Expr { }
record Add(Expr left, Expr right) implements Expr { }
record Mul(Expr left, Expr right) implements Expr { }
record Neg(Expr inner) implements Expr { }
public class ExprTreeDemo { static int eval(Expr e) { return switch (e) { case Num(int v) -> v; case Add(Expr l, Expr r) -> eval(l) + eval(r); case Mul(Num(int a), Expr r) when a == 0 -> 0; case Mul(Expr l, Expr r) -> eval(l) * eval(r); case Neg(Expr inner) -> -eval(inner); }; }
static String show(Expr e) { return switch (e) { case Num(int v) -> String.valueOf(v); case Add(Expr l, Expr r) -> "(" + show(l) + " + " + show(r) + ")"; case Mul(Expr l, Expr r) -> show(l) + " * " + show(r); case Neg(Expr inner) -> "-" + show(inner); }; }
public static void main(String[] args) { Expr a = new Add(new Num(2), new Mul(new Num(3), new Num(4))); Expr b = new Mul(new Neg(new Add(new Num(10), new Num(5))), new Num(2)); // 0 * (anything): the guard skips work on the right side Expr c = new Mul(new Num(0), b);
for (Expr e : new Expr[] {a, b, c}) { System.out.println(show(e) + " = " + eval(e)); } }}(2 + 3 * 4) = 14 -(10 + 5) * 2 = -30 0 * -(10 + 5) * 2 = 0
What this code does
- Each case names a node's children and calls
evalon them; the recursion stops atNum.Expris sealed, so the compiler checks thatNum,Add,MulandNegare all handled, with nodefault. case Mul(Num(int a), Expr r) when a == 0looks two levels deep to spot "zero times anything" and returns 0 without evaluating the right side. It sits before the generalMulcase, which still covers every multiplication.
To evaluate the tree, switch on the node with record patterns: case Add(Expr l, Expr r) -> eval(l) + eval(r). Each case names its children and calls eval on them. This is recursion: a method that calls itself on smaller parts until it reaches a Num. Nested patterns can also spot special shapes, such as multiplying by zero: case Mul(Num(int a), Expr r) when a == 0 -> 0. Because Expr is sealed, the compiler checks that every node type is handled.
Next step
Check your understanding
12 quick questions