Sitemap
Syed Nazeer

Syed Nazeer

I'm a Java enthusiast, developing passion for technical content creation.

Record class vs Record Pattern

2 min readJun 1, 2026

Records vs Record Patterns in Java, using examples and real-world context.

1. What is a Record?

A record is a data carrier (a special class) used to store immutable data.

Example

record Person(String name, int age) {}

Purpose

  • Represent data (DTO / model)
  • Reduce boilerplate (getters, constructor, equals, hashCode)

2. What is a Record Pattern?

A record pattern is used to extract (deconstruct) data from a record while performing type checking.

Example

if (obj instanceof Person(String name, int age)) {
System.out.println(name + " " + age);
}

Purpose

  • Extract fields from records
  • Combine type check + cast + data access

Key Difference (Core Idea)

Press enter or click to view image in full size

Side-by-Side Example

Same Scenario

Using Record (Data Definition)

record Person(String name, int age) {}
Person p = new Person("Nazeer", 30);
System.out.println(p.name()); // getter

Using Record Pattern (Data Extraction)

Object obj = new Person("Nazeer", 30);
if (obj instanceof Person(String name, int age)) {
System.out.println(name); // directly extracted
}

Real-World Analogy

Think like this:

  • Record = 📦 Box (contains data)
  • Record Pattern = 📤 Unpacking the box

Where Each is Used

Get Syed Nazeer’s stories in your inbox

Join Medium for free to get updates from this writer.

Record is used in:

  • DTOs (Spring Boot APIs)
  • Request/Response models
  • Database projections
  • Event payloads

Record Pattern is used in:

  • Service layer logic
  • Switch-based routing
  • Event handling (Kafka)
  • Polymorphic APIs

Combined Usage (REAL SCENARIO)

They are designed to work together

record Order(String id, double amount) {}
static String process(Object obj) {
return switch (obj) {
case Order(String id, double amount) ->
"Order " + id + " for ₹" + amount;
default -> "Unknown";
};
}

Key Benefits Comparison

Records

  • Less boilerplate
  • Immutable
  • Clean DTOs

Record Patterns

  • No casting
  • No getters needed
  • Cleaner logic
  • Safer (compile-time checks)

Interview One-Liner

“Records are used to define immutable data objects, while record patterns are used to destructure those objects by extracting their fields during pattern matching.”

Common Mistake (Important)

Many people think: “Record pattern is a type like record”

Correct:

  • Record = class
  • Record Pattern = syntax/feature

When to Use Together

✔ Modern Java (21+)

✔ Microservices (Spring Boot)

✔ Event-driven design

✔ Clean architecture

--

--

Syed Nazeer
Syed Nazeer

Written by Syed Nazeer

I'm a Java enthusiast, developing passion for technical content creation.