Java Records
A record is a class whose whole job is to carry a fixed set of values. You list the components once and the compiler writes the fields, constructor, accessors, equals, hashCode and toString. This page explains what is generated and how, then shows records in real use, their serialization guarantee, and the traps that surprise people moving from ordinary classes.
Contents
What a record is and how it works The generated members, checked one by one Adding behaviour: methods, static members and local records Records in everyday code: map keys and multiple return values Records are only shallowly immutable Traps: accessors, floating point and mutable keys Serialization goes through the constructor Which one to use
What a record is and how it works
Many classes exist only to hold a few values: a point, a money amount, a row from a query, the result of a method that returns two things. Written by hand, such a class needs private final fields, a constructor, getters, equalshashCodetoStringrecord Point(int x, int y) {}
The list in parentheses is the record's state description, and each entry is a component. A record is defined by its components and nothing else, which is why the language can safely generate everything. From the component list the compiler creates:
- a
field per component, and no other instance fields are allowed;private final - a public canonical constructor whose parameters match the components in order;
- a public accessor per component, named exactly like it:
, notx() ;getX() ,equals andhashCode that use every component.toString
Underneath, a record is an ordinary class that is finaljava.lang.RecordRecordgetRecordComponents()equalshashCodetoStringjavap -cinvokedynamicjava.lang.runtime.ObjectMethods.bootstrap
| Feature | Since | Best for |
|---|---|---|
| Records as a preview (JEP 359, then JEP 384) | Java 14 and 15 | Historical only; do not use preview builds for this today |
| Records final (JEP 395), local records, static members in inner classes | Java 16 | Data carriers, DTOs, map keys, multiple return values |
Records in sealed | Java 17 | Closed sets of data types, such as the result of a parser |
Record patterns in instanceofswitch | Java 21 | Taking a record apart into its components |
All programs on this page are complete classes, compiled and run on JDK 21. Save one as ClassName.javajava ClassName.java
The generated members, checked one by one
The program creates two points with the same values, checks each generated member, then uses reflection to confirm what the compiler built and to try to change a field.
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.RecordComponent;
import java.util.HashSet;
import java.util.Set;
public class RecordBasics {
record Point(int x, int y) {
}
public static void main(String[] args) throws Exception {
Point a = new Point(3, 7);
Point b = new Point(3, 7);
System.out.println("accessors: x()=" + a.x() + ", y()=" + a.y());
System.out.println("toString: " + a);
System.out.println("a == b: " + (a == b));
System.out.println("a.equals(b): " + a.equals(b));
System.out.println("same hash: " + (a.hashCode() == b.hashCode()));
Set<Point> set = new HashSet<>(Set.of(a));
set.add(b);
System.out.println("set size after adding an equal point: " + set.size());
// What the compiler generated
Class<Point> c = Point.class;
System.out.println("superclass: " + c.getSuperclass().getName());
System.out.println("final class: " + Modifier.isFinal(c.getModifiers()));
for (RecordComponent rc : c.getRecordComponents()) {
Field f = c.getDeclaredField(rc.getName());
System.out.println("component " + rc.getName() + ": field is "
+ Modifier.toString(f.getModifiers()));
}
// Even reflection cannot change a record field
Field x = c.getDeclaredField("x");
x.setAccessible(true);
try {
x.setInt(a, 99);
} catch (IllegalAccessException e) {
System.out.println("reflective write: IllegalAccessException, x is still " + a.x());
}
}
}
Output:
accessors: x()=3, y()=7
toString: Point[x=3, y=7]
a == b: false
a.equals(b): true
same hash: true
set size after adding an equal point: 1
superclass: java.lang.Record
final class: true
component x: field is private final
component y: field is private final
reflective write: IllegalAccessException, x is still 3
is false because there are two objects, buta == b is true and the hash codes match because both compare component values. That is why theequals still has size 1 after adding the second point.HashSet- The superclass is
and the class isjava.lang.Record . A record cannot extend another class, and nothing can extend a record.final - Both component fields are
.private final normally lets reflection write a final field. Records are excluded on purpose, sosetAccessible(true) throwssetInt andIllegalAccessException is still 3. Libraries that create records, such as Jackson and Java serialization, must go through the canonical constructor.x
Adding behaviour: methods, static members and local records
A record body can contain instance methods, static fields, static factory methods, nested types and extra constructors, and the record can implement interfaces. The MoneylongComparablemain
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class RecordFeatures {
// Records can implement interfaces, declare static members and add methods
record Money(long cents, String currency) implements Comparable<Money> {
static final Money ZERO_USD = new Money(0, "USD");
static Money usd(String amount) {
return new Money(new BigDecimal(amount).movePointRight(2).longValueExact(), "USD");
}
Money plus(Money other) {
if (!currency.equals(other.currency)) {
throw new IllegalArgumentException(currency + " vs " + other.currency);
}
return new Money(cents + other.cents, currency); // a new record, never a change
}
@Override
public int compareTo(Money o) {
return Long.compare(cents, o.cents);
}
@Override
public String toString() {
return String.format("%s %d.%02d", currency, cents / 100, cents % 100);
}
}
public static void main(String[] args) {
Money total = Money.ZERO_USD;
List<Money> items = List.of(Money.usd("4.50"), Money.usd("12.25"), Money.usd("0.99"));
for (Money m : items) {
total = total.plus(m);
}
System.out.println("total: " + total);
Money largest = items.stream().max(Comparator.naturalOrder()).orElseThrow();
System.out.println("largest: " + largest);
// A local record: a named tuple for an intermediate result inside one method
record Line(String item, int qty) {
}
List<Line> lines = new ArrayList<>(List.of(new Line("pen", 3), new Line("pad", 1)));
lines.sort(Comparator.comparingInt(Line::qty));
System.out.println("sorted lines: " + lines);
try {
total.plus(new Money(100, "EUR"));
} catch (IllegalArgumentException e) {
System.out.println("mixed currencies rejected: " + e.getMessage());
}
}
}
Output:
total: USD 17.74
largest: USD 12.25
sorted lines: [Line[item=pad, qty=1], Line[item=pen, qty=3]]
mixed currencies rejected: USD vs EUR
- The total is exactly USD 17.74: 450 + 1225 + 99 = 1774 cents.
parses withusd andBigDecimal , so an input with three decimal places throws instead of being rounded silently.longValueExact returns a newplus instead of changing this one. Every "modifying" operation on a record should work this way A method that changes one component is usually named after it, such asMoney .withCents(long) withmax found USD 12.25 becauseComparator.naturalOrder() compares cents.compareTo- The local record
exists only insideLine . Local and nested records are implicitlymain , so they cannot capture local variables or the enclosing instance.static - The custom
replaced the generated one. You can override any generated member, but an override must keep the contract described in thetoString Javadoc: a copy made from the accessors must be equal to the original.Record
Records in everyday code: map keys and multiple return values
The two jobs where records save the most code are composite keys and small result types. The sales list is chosen so that two Oslo 2024 entries must be merged under one key, and so the minimum and maximum come from different cities.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class RecordsInPractice {
record Sale(String city, int year, int amount) {
}
// A composite map key: equals and hashCode come for free
record CityYear(String city, int year) implements Comparable<CityYear> {
@Override
public int compareTo(CityYear o) {
int c = city.compareTo(o.city);
return c != 0 ? c : Integer.compare(year, o.year);
}
}
// A generic record used to return two values from one method
record MinMax<T>(T min, T max) {
}
static MinMax<Integer> minMax(List<Integer> values) {
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int v : values) {
min = Math.min(min, v);
max = Math.max(max, v);
}
return new MinMax<>(min, max);
}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("Oslo", 2024, 120), new Sale("Oslo", 2025, 80),
new Sale("Lima", 2025, 200), new Sale("Oslo", 2024, 30),
new Sale("Lima", 2025, 50));
Map<CityYear, Integer> totals = sales.stream().collect(Collectors.groupingBy(
s -> new CityYear(s.city(), s.year()), TreeMap::new,
Collectors.summingInt(Sale::amount)));
totals.forEach((k, v) -> System.out.println(k + " -> " + v));
System.out.println("lookup Oslo 2024: " + totals.get(new CityYear("Oslo", 2024)));
MinMax<Integer> mm = minMax(sales.stream().map(Sale::amount).toList());
System.out.println(mm + ", spread " + (mm.max() - mm.min()));
}
}
Output:
CityYear[city=Lima, year=2025] -> 250
CityYear[city=Oslo, year=2024] -> 150
CityYear[city=Oslo, year=2025] -> 80
lookup Oslo 2024: 150
MinMax[min=30, max=200], spread 170
- Oslo 2024 appears twice in the input (120 and 30) and once in the result with 150.
relies ongroupingBy andequals of the key, which the record supplies. Before records, the usual shortcut was a string key such ashashCode , which breaks as soon as a city contains the separator."Oslo|2024" - The lookup with a freshly created
finds 150, because a key is found by value, not by identity.new CityYear("Oslo", 2024) - The
sorts byTreeMap , so Lima comes before Oslo and 2024 before 2025.compareTo shows that records can be generic. Returning a record is clearer than returning anMinMax<T> or aint[2] , because the caller readsMap.Entry instead ofmm.max() .result[1]
Records are only shallowly immutable
A finalArrayList
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ShallowImmutability {
record Team(String name, List<String> members) {
}
record Samples(int[] values) {
}
public static void main(String[] args) {
// The field is final, but the list it points to is not
List<String> names = new ArrayList<>(List.of("Ana", "Ben"));
Team team = new Team("core", names);
names.add("Cho");
System.out.println("team after caller changed its list: " + team);
team.members().add("Dev");
System.out.println("team after changing members(): " + team);
// Arrays are compared by reference in the generated equals
Samples s1 = new Samples(new int[] {1, 2, 3});
Samples s2 = new Samples(new int[] {1, 2, 3});
System.out.println("records with equal arrays equal: " + s1.equals(s2));
System.out.println("arrays equal by content: "
+ Arrays.equals(s1.values(), s2.values()));
System.out.println("toString shows: " + s1.toString().replaceAll("@\\w+", "@..."));
}
}
Output:
team after caller changed its list: Team[name=core, members=[Ana, Ben, Cho]]
team after changing members(): Team[name=core, members=[Ana, Ben, Cho, Dev]]
records with equal arrays equal: false
arrays equal by content: true
toString shows: Samples[values=[I@...]
- "Cho" appears in the record because the caller kept a reference to the same list. "Dev" appears because
returns that list too. The fix is a defensive copy,members() , in a compact constructor; seemembers = List.copyOf(members)record compact constructors . - Two records holding identical arrays are not equal, although
says the arrays are. The generatedArrays.equals calls each component's ownequals , and for an array that isequals .== printstoString and an identity hash (shortened here) instead of the numbers. Prefer a[I@ component, or override all three methods withList ,Arrays.equals andArrays.hashCode .Arrays.toString
Traps: accessors, floating point and mutable keys
Three behaviours of the generated methods surprise people who know ordinary classes. The program shows each one with the smallest input that triggers it: two codes that differ only in case, the two zeros and NaN, and a list changed after it was used as a key.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RecordPitfalls {
// An overridden accessor does not change what equals compares
record Code(String value) {
@Override
public String value() {
return value.toUpperCase();
}
}
record Reading(double celsius) {
}
record Basket(List<String> items) {
}
public static void main(String[] args) {
Code lower = new Code("abc");
Code upper = new Code("ABC");
System.out.println("accessors: " + lower.value() + " and " + upper.value());
System.out.println("equal records: " + lower.equals(upper));
System.out.println("toString: " + lower);
// double components are compared like Double.compare, not like ==
System.out.println("0.0 == -0.0: " + (0.0 == -0.0));
System.out.println("Reading(0.0) eq (-0.0): "
+ new Reading(0.0).equals(new Reading(-0.0)));
System.out.println("NaN == NaN: " + (Double.NaN == Double.NaN));
System.out.println("Reading(NaN) eq (NaN): "
+ new Reading(Double.NaN).equals(new Reading(Double.NaN)));
// A mutable component changes the hash code of a key already in a set
List<String> items = new ArrayList<>(List.of("tea"));
Basket basket = new Basket(items);
Set<Basket> set = new HashSet<>(Set.of(basket));
items.add("milk");
System.out.println("set contains the same basket: " + set.contains(basket));
System.out.println("set size: " + set.size() + ", iterates to: " + set.iterator().next());
}
}
Output:
accessors: ABC and ABC
equal records: false
toString: Code[value=abc]
0.0 == -0.0: true
Reading(0.0) eq (-0.0): false
NaN == NaN: false
Reading(NaN) eq (NaN): true
set contains the same basket: false
set size: 1, iterates to: Basket[items=[tea, milk]]
- Both accessors return "ABC", yet the records are not equal and
showstoString . The generated methods read the field, not the accessor, as theabc design described above implies. If you need normalized values, normalize them in the constructor, not in the accessor.invokedynamic - Primitive components are compared the way
andDouble.compare compare, not withFloat.compare . So== andReading(0.0) are not equal althoughReading(-0.0) is true, and two NaN readings are equal although0.0 == -0.0 is false. This keepsNaN == NaN reflexive, which hash-based collections need.equals - After "milk" is added to the list, the set no longer finds the basket although it still holds it: size 1, and iterating shows
. The hash code changed, so the lookup searches the wrong bucket. A record used as a key must have only immutable components.[tea, milk]
Serialization goes through the constructor
Ordinary Serializable
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class RecordSerialization {
record Range(int lo, int hi) implements Serializable {
Range {
System.out.println(" Range constructor runs for " + lo + ".." + hi);
if (lo > hi) {
throw new IllegalArgumentException("lo > hi");
}
}
}
static class OldRange implements Serializable {
private static final long serialVersionUID = 1L;
final int lo;
final int hi;
OldRange(int lo, int hi) {
System.out.println(" OldRange constructor runs for " + lo + ".." + hi);
this.lo = lo;
this.hi = hi;
}
}
public static void main(String[] args) throws Exception {
System.out.println("creating:");
Range r = new Range(1, 5);
OldRange o = new OldRange(1, 5);
System.out.println("deserializing the record:");
Range r2 = (Range) roundTrip(r);
System.out.println(" result " + r2 + ", equal: " + r.equals(r2));
System.out.println("deserializing the class:");
OldRange o2 = (OldRange) roundTrip(o);
System.out.println(" result lo=" + o2.lo + " hi=" + o2.hi + " (no constructor call)");
}
static Object roundTrip(Object value) throws IOException, ClassNotFoundException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bytes)) {
out.writeObject(value);
}
try (ObjectInputStream in =
new ObjectInputStream(new ByteArrayInputStream(bytes.toByteArray()))) {
return in.readObject();
}
}
}
Output:
creating:
Range constructor runs for 1..5
OldRange constructor runs for 1..5
deserializing the record:
Range constructor runs for 1..5
result Range[lo=1, hi=5], equal: true
deserializing the class:
result lo=1 hi=5 (no constructor call)
The record's constructor ran twice, once when the program created it and once during readObjectlo > hiserialVersionUIDreadObjectwriteObject
Which one to use
| Need | Record | Regular class | Lombok @Value |
|---|---|---|---|
| Extend another class | No, always extends Record | Yes | Yes |
| Be subclassed | No, implicitly final | Yes, unless final | No, final by default |
| Extra instance fields | No | Yes | Yes |
| Hide the internal representation | No, every component has a public accessor | Yes | No, a getter per field by default |
Generated equalshashCodetoString | Yes, by the language | No | Yes, by an annotation processor |
| Deconstruct with record patterns | Yes | No | No |
| Safe deserialization through the constructor | Yes | No | No |
- Use a record when the type is its data: coordinates, money, DTOs, query results, events, map keys, results with several values.
- Keep a regular class when the object has changing state, when its identity matters (an open connection, an entity tracked by an ORM), or when its fields are an implementation detail that might change.
- JPA entities cannot be records, because JPA needs a no-argument constructor and mutable fields. Records work well for the projections and DTOs around them.
Next steps: validating and normalizing components in