The 30 second answer
A record, final in Java 16, is a short way to declare a class that just carries data. From one line, the compiler generates private final fields, a constructor, accessor methods, and equals, hashCode and toString based on all the fields. I use them for DTOs, value objects, map keys and returning several values. Validation goes in a compact constructor.
record Point(int x, int y) {}
record Money(long cents, String currency) {
Money { // compact canonical constructor
if (cents < 0) throw new IllegalArgumentException("negative");
Objects.requireNonNull(currency);
}
Money plus(Money o) { return new Money(cents + o.cents, currency); }
}
var p = new Point(1, 2);
p.x(); // accessor is x(), not getX()
p.equals(new Point(1, 2)); // trueRecords can implement interfaces and have static fields, static and instance methods, and nested types. They can also be declared locally inside a method. Records were previewed in Java 14 and 15 and became final in Java 16. Jackson and Spring Boot can bind JSON and configuration properties to records, which makes them a good fit for request and response DTOs.
- Why and when. JEP 395 calls records "classes that act as transparent carriers for immutable data", or nominal tuples. They remove the constructor, accessor, equals, hashCode and toString boilerplate of plain data carriers. They were a preview in JDK 14 (JEP 359), a second preview in JDK 15 (JEP 384), and final in JDK 16 (JEP 395). The JEP says the goal is modeling immutable data, not a "war on boilerplate" for mutable JavaBeans.
- Syntax and generated members. A record such as
record Point(int x, int y) {}gets, for each component, a private final field and a public accessor with the same name (x(), notgetX()). It also gets a canonical constructor that assigns every field, and equals, hashCode and toString based on all components. A compact constructor (Point { ... }) validates or normalizes the arguments without repeating the parameter list, and the fields are assigned for you afterwards. - Restrictions. A record has no extends clause, because its superclass is always
java.lang.Record. It is implicitly final and cannot be abstract. It cannot declare instance fields, instance initializers or native methods. A nested record is implicitly static. It may still implement interfaces and declare static fields, static methods and its own instance methods. Serialization follows the components and the canonical constructor and can't be customized withwriteObjectorreadObject. - When to use it versus a class. Use a record for values defined entirely by their data: DTOs, API responses, map keys, events, query results and snapshots. Use a regular class when you need mutable state, inheritance, hidden internal state, or identity-based equality such as a JPA entity.
- Immutability and concurrency. The Record Javadoc says records are shallowly immutable. Fields are final, so a properly constructed record is safe to share between threads without locks. A component that is a mutable
Listor array can still change, though, so copy it in the compact constructor withList.copyOforMap.copyOf. That is why records pair well with anAtomicReferencesnapshot: each write builds a new record and swaps it in, and readers never see a half-built one.
import java.util.List;
public class Money {
record Price(String sku, long cents, List<String> tags) {
Price { // compact canonical constructor
if (cents < 0) throw new IllegalArgumentException("negative price");
tags = List.copyOf(tags); // defensive copy: records are only shallowly immutable
}
Price withCents(long newCents) { // "wither": return a new record, never mutate
return new Price(sku, newCents, tags);
}
}
public static void main(String[] args) {
Price a = new Price("shoe", 5_000, List.of("sale"));
Price b = new Price("shoe", 5_000, List.of("sale"));
System.out.println(a); // Price[sku=shoe, cents=5000, tags=[sale]]
System.out.println(a.equals(b) + " " + (a.hashCode() == b.hashCode())); // true true
System.out.println(a.withCents(4_500).cents() + " " + a.cents()); // 4500 5000
}
}Verified with OpenJDK 21.0.13: it prints the generated toString, true true for equals and hashCode, and 4500 5000, which shows the original record is unchanged.
Sources (5)
- JEP 395: Records (final in JDK 16)openjdk.org
- JEP 359: Records (Preview, JDK 14)openjdk.org
- JLS 21 section 8.10: Record Classesdocs.oracle.com
- Oracle Java 21 language guide: Record Classesdocs.oracle.com
- Record Javadoc (Java 21): shallowly immutable carriersdocs.oracle.com