Every Java codebase is full of small classes that just carry data: an Employee, an OrderLine, an API request, a row from a query. And for years, each of those classes looked the same: private fields, a constructor, getters, equals, hashCode, toString. Forty lines of code to say “an employee has a name and a designation”.
Records fix that. This is the whole thing:
record Employee(String name, String designation) {}
Records arrived as a preview in Java 14 and became a standard feature in Java 16 (JEP 395). Java 21 builds on them with record patterns, which make records even more useful. Here’s everything you need.
The problem: the boilerplate class
Here is the “before” version of Employee, written properly:
// Java · Employee.java (the old way)
public final class Employee {
private final String name;
private final String designation;
public Employee(String name, String designation) {
this.name = name;
this.designation = designation;
}
public String getName() { return name; }
public String getDesignation() { return designation; }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Employee other)) return false;
return Objects.equals(name, other.name)
&& Objects.equals(designation, other.designation);
}
@Override
public int hashCode() { return Objects.hash(name, designation); }
@Override
public String toString() {
return "Employee[name=" + name + ", designation=" + designation + "]";
}
}
The real information is two field names and their types. Everything else is ceremony. And ceremony causes bugs: add a department field, forget to update equals, and two different employees suddenly compare as equal. Tools like Lombok (@Data, @Value) or IDE generators helped, but the code (or the annotation magic) was still there to maintain.
What a record gives you
// Java 16+ · Employee.java
record Employee(String name, String designation) {}
The part in brackets is the record’s header, and its entries are called components. From that one line, the compiler generates:
- A
private finalfield for each component. - A canonical constructor taking all components, in order.
- An accessor method for each component, named after it:
name()anddesignation(). equals()andhashCode()based on all components.toString()that prints all components.
It also makes the class final (nobody can extend it), and every record implicitly extends java.lang.Record.
// Java · using it
var asha = new Employee("Asha", "Architect");
asha.name(); // "Asha"
asha.designation(); // "Architect"
System.out.println(asha); // Employee[name=Asha, designation=Architect]
asha.equals(new Employee("Asha", "Architect")); // true: same data, equal
The benefits
Far less code. One line instead of forty. Less to read, review and get wrong.
Correct equals and hashCode, always. They’re generated from the components, so they can’t drift out of date when you add a field. Records work safely as HashMap keys and in HashSets.
Immutable by design. Fields are final and there are no setters. Once an Employee exists, it can’t change. Immutable objects are easier to reason about and safe to share between threads, which matters more than ever with virtual threads.
Clear intent. When a reader sees record, they know immediately: this is plain data, two objects with the same data are equal, nothing hidden.
A useful toString() for free. Logs show Employee[name=Asha, designation=Architect] instead of Employee@1b6d3586.
“A record is a class that says, in its own declaration, “I am my data, and nothing else.””
Doing more with records
A record is still a class. You can add to it, within a few rules.
Validation with a compact constructor
Want to reject bad data? Use a compact constructor: no parameter list, no field assignments. The compiler assigns the fields after your code runs, so you can check, and even normalise, the values:
// Java · Salary.java
record Salary(String currency, long amount) {
Salary {
Objects.requireNonNull(currency, "currency");
if (amount < 0) throw new IllegalArgumentException("amount must be >= 0");
currency = currency.toUpperCase(); // normalise before it's stored
}
}
new Salary("inr", 100); // Salary[currency=INR, amount=100]
new Salary("INR", -5); // IllegalArgumentException
Now an invalid Salary can never exist anywhere in your program.
Methods, static factories and interfaces
// Java · Salary.java, continued
record Salary(String currency, long amount) implements Comparable<Salary> {
static Salary inr(long amount) { // static factory
return new Salary("INR", amount);
}
Salary add(Salary other) { // instance method
if (!currency.equals(other.currency)) throw new IllegalArgumentException("currency mismatch");
return new Salary(currency, amount + other.amount); // returns a NEW record
}
@Override
public int compareTo(Salary other) { return Long.compare(amount, other.amount); }
}
Records can have static fields, static methods, instance methods, nested types, and can implement any interface.
“Changing” a record: return a copy
Because records are immutable, you don’t change one, you make a new one. A small with method keeps this readable:
record Employee(String name, String designation) {
Employee withDesignation(String newDesignation) {
return new Employee(name, newDesignation);
}
}
var promoted = asha.withDesignation("Principal Architect");
Local records
You can declare a record inside a method. Perfect for a temporary grouping in the middle of a stream, instead of juggling Map.Entry or Object[]:
// Java · inside a method
record DesignationCount(String designation, long count) {}
List<DesignationCount> counts = employees.stream()
.collect(groupingBy(Employee::designation, counting()))
.entrySet().stream()
.map(e -> new DesignationCount(e.getKey(), e.getValue()))
.toList();
The rules: what a record can’t do
- It can’t extend another class. It already extends
java.lang.Record. (It can implement interfaces.) - It can’t be extended. Records are always
final. - No extra instance fields. All state must be in the header. Static fields are fine.
- Fields can’t be reassigned. No setters, no mutation.
Watch out: immutability is shallow
A record’s fields are final, but the objects they point to might not be. If a component is a mutable List, someone can still change the list:
// Java · defensive copy in the compact constructor
record Team(String name, List<Employee> members) {
Team {
members = List.copyOf(members); // an unmodifiable copy
}
}
List.copyOf takes a snapshot, so changes to the caller’s list don’t leak in, and team.members().add(...) throws UnsupportedOperationException. Do the same with Set.copyOf and Map.copyOf.
Where records fit, and where they don’t
Great fits:
- DTOs: REST request and response bodies.
- Value objects:
Money,Email,DateRange,Coordinates. - Query results and projections (Spring Data supports record projections).
- Map keys and compound keys.
- Events and messages passed between services or components.
- Returning several values from a method.
Poor fits:
- JPA / Hibernate entities. Entities need a no-argument constructor, mutable fields and often subclass proxies. Records have none of these. Use records for the DTOs around your entities instead.
- Objects with changing state, like a shopping cart that items are added to over time.
- Classes that need inheritance.
What Java 21 adds: record patterns
Java 21 made record patterns (JEP 440) and pattern matching for switch (JEP 441) standard. Together they let you check a record’s type and pull its components out in one step.
// Before: check, cast, then call accessors
if (obj instanceof Point p) {
int x = p.x();
int y = p.y();
System.out.println(x + y);
}
// Java 21: deconstruct the record directly
if (obj instanceof Point(int x, int y)) {
System.out.println(x + y);
}
The real power shows up with sealed interfaces. When the compiler knows every possible implementation, a switch can cover them all, without a default:
// Java 21 · Shapes.java
sealed interface Shape permits Circle, Square, Rectangle {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square s -> s.side() * s.side();
case Rectangle(double w, double h) -> w * h;
};
}
Add a new Triangle record to the permits list and every switch that doesn’t handle it stops compiling. That’s a bug caught by the compiler instead of in production. Sealed types plus records is how modern Java models “one of these few shapes of data”. The full story: pattern matching for switch.
Key takeaways
record Employee(String name, String designation) {}generates fields, constructor, accessors,equals,hashCodeandtoString.- Accessors are
name(), notgetName(). - Records are final and immutable, so they’re safe to share and correct to compare.
- Use a compact constructor for validation and normalisation; use
List.copyOffor collection components. - Records are ideal for DTOs, value objects, events and projections, but not JPA entities.
- Java 21 record patterns let
instanceofandswitchunpack records, and sealed interfaces make those switches exhaustive.
Frequently asked questions
What is a record in Java?
A special kind of class for holding immutable data. You declare its components in a header, and the compiler generates the constructor, accessors, equals, hashCode and toString.
Which Java version introduced records?
Records were previewed in Java 14 and 15 and became a standard feature in Java 16. Java 21 added record patterns for instanceof and switch.
Can a Java record have methods?
Yes. Records can have instance methods, static methods, static fields, and can implement interfaces. They can’t have extra instance fields or extend another class.
Are Java records immutable?
Their fields are final and there are no setters, so the record itself is immutable. If a component is a mutable object such as a List, make a defensive copy in the compact constructor.
Can I use records instead of Lombok?
For immutable data classes, often yes: a record replaces @Value with plain Java and no annotation processor. Lombok still covers cases records don’t, such as mutable classes and builders.
Next in Modern Java: var, letting the compiler write the type for you.
Comments