Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Object-Oriented Programming

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.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Object-Oriented Programming

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
The nested pattern Bag(String owner, Flight(String code, String to), int kg) opens the Bag: owner becomes Hana and kg becomes 21. Then it opens the Flight inside: code becomes BA-131 and to becomes London. Four variables from one test. Bag(String owner, Flight(String code, String to), int kg) Bag owner "Hana" kg 21 Flight code "BA-131", to "London" ready variables owner, code, to, kg
Two records opened in one test: first the Bag, then the Flight inside it.

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):

PatternResult
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

PatternWhat you get
scan instanceof Bag bagthe 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 typeone case per record, no default

Any mismatch with the header is a compile error, not a surprise at run time.

Keep going in Java · 44 of 79

Previous
Java Pattern Matching with instanceof and switch
Next post
Java equals and hashCode: Why a HashSet Needs Both
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • A type pattern, then getters
  • Take the fields out in the test
  • A pattern inside a pattern
  • Records only, and the header must match
  • A switch that misses nothing
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.