Java Record Patterns: Unpacking a Record
scan instanceof Bag(String owner, Flight flight, int kg) tests the type and hands you owner, flight and kg with no getters. Nest Flight(String code, String to) to print Hana flies BA-131 to London, and a sealed baggage desk sends a 27 kg suitcase to the heavy belt.
What you will learn
- Test a record's type and copy its components into variables in one step
- Explain why a record pattern works on records but not plain classes
- Nest one record pattern inside another
- Use record patterns in a switch over a sealed interface with no default
Before you start
- Java records
- Java pattern matching with instanceof and switch
A record pattern is how Java unpacks a record for you. With one test, you check the type and take the fields out in the same step.
A type pattern, then getters
package org.studyeasy.s05l04;
public class Ex01_GetterWay {
record Flight(String code, String to) {}
record Bag(String owner, Flight flight, int kg) {}
public static void main(String[] args) {
Object scan = new Bag("Hana", new Flight("BA-131", "London"), 21);
// Type pattern (last lecture): test and name the whole Bag
if (scan instanceof Bag bag) {
// then ask for each field with its getter
String owner = bag.owner();
int kg = bag.kg();
System.out.println(owner + ": " + kg + " kg");
}
}
}
Hana: 21 kg
A Bag holds a Flight, so there's a record inside a record. The type pattern scan instanceof Bag bag gives one variable for the whole record, and then you take each field out yourself, one line per field. (The accessor is owner(); getOwner() is "cannot find symbol".)
Take the fields out in the test
// Record pattern: test the type AND take out every field
if (scan instanceof Bag(String owner, Flight flight, int kg)) {
System.out.println(owner + ": " + kg + " kg");
System.out.println("Flight: " + flight.code());
}
Hana: 21 kg
Flight: BA-131
The test and the unpacking are one line, and owner, flight and kg are ready inside the block. Behind the scenes, once the test passes, Java calls the accessors for you and copies each component into its own variable. flight is a whole Flight object, so you still call flight.code() for its code.
The pattern copies the record header: Bag(String owner, Flight flight, int kg), same order and same types. If scan held a String instead, the test would fail, nothing would be unpacked and the block would be skipped.
A pattern inside a pattern
// Nested: open the Flight inside the Bag as well
if (scan instanceof Bag(String owner,
Flight(String code, String to),
int kg)) {
System.out.println(owner + " flies " + code + " to " + to);
}
Hana flies BA-131 to London
In the Flight slot, instead of Flight flight, you write another pattern. Java asks "is it a Bag?" and opens it, then "is the flight a Flight?" and opens that too. Four variables, no getters. Wherever a component is itself a record, you can write its pattern right in that slot.
Records only, and the header must match
A type pattern such as instanceof Crate crate works on any class. A record pattern on a plain class, Crate(String label), doesn't compile: deconstruction patterns can only be applied to records. A plain class has no components to take out. The pattern must also match the header exactly. For record Pen(String color, int price):
| Pattern | Result |
|---|---|
Pen(String color, int price) | compiles |
Pen(String color) | incorrect number of nested patterns |
Pen(int price, String color) | incompatible types: String cannot be converted to int |
A switch that misses nothing
package org.studyeasy.s05l04;
public class Ex04_SealedSwitch {
sealed interface Item permits Suitcase, Pet, Oversize {}
record Suitcase(String tag, int kg) implements Item {}
record Pet(String name, String kind) implements Item {}
record Oversize(String what) implements Item {}
static String desk(Item item) {
return switch (item) { // sealed: no default needed
case Suitcase(String tag, int kg) when kg > 23 ->
"Heavy belt: " + tag;
case Suitcase s -> "Belt 1: " + s.tag();
case Pet(String name, String kind) -> "Pet desk: " + name;
case Oversize(String what) -> "Oversize gate: " + what;
};
}
public static void main(String[] args) {
Item[] items = {
new Suitcase("BLR-1042", 18), new Suitcase("DEL-7710", 27),
new Pet("Bruno", "beagle"), new Oversize("golf bag") };
for (Item item : items) System.out.println(desk(item));
}
}
Belt 1: BLR-1042
Heavy belt: DEL-7710
Pet desk: Bruno
Oversize gate: golf bag
The sealed interface permits three records, so Java knows every Item and the switch needs no default. The first case is a record pattern with a guard: DEL-7710 weighs 27, over 23, so it goes to the heavy belt. BLR-1042 weighs 18, fails the guard and lands on the plain Suitcase s case. Pet and Oversize unpack their own components. Add a Cabin record to the permits list without a case and desk won't compile: the switch doesn't cover all possible input values.
Recap
| Pattern | What you get |
|---|---|
scan instanceof Bag bag | the whole record; then call getters |
scan instanceof Bag(String owner, Flight flight, int kg) | one variable per component |
nested Flight(String code, String to) | the inner record opened too |
| switch over a sealed type | one case per record, no default |
Any mismatch with the header is a compile error, not a surprise at run time.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
