Java records explained with examples

Java records with examples: what the compiler generates, compact constructors for validation, immutability and defensive copies, record patterns in Java 21, and when not to use a record.

Written for JDK 21 (records are final since JDK 16; record patterns since JDK 21)

A record is a class whose job is to carry data. You list its fields once, in the header, and the compiler writes the constructor, the accessors, equals, hashCode and toString for you. Records became a standard feature in Java 16 (JEP 395), and Java 21 added record patterns, which take them apart again. This tutorial covers both, along with the validation and immutability details that decide whether a record fits.

A record in one line

Java
public record Point(int x, int y) {}

That line declares a final class with two private final fields and everything a value type needs:

Java
Point p = new Point(3, 4);
p.x();                          // 3
p.equals(new Point(3, 4));      // true
p.hashCode() == new Point(3, 4).hashCode(); // true
System.out.println(p);          // Point[x=3, y=4]

The equivalent hand-written class is around 40 lines: two fields, a constructor, two getters, and the three Object methods. The accessors are named after the components, x() rather than getX(), which matters for some older frameworks that look for JavaBean getters.

Two records are equal when all their components are equal. equals compares each component with equals (or == for primitives), and hashCode combines them, so records work as map keys and in sets without extra code.

Validate in a compact constructor

The header's parameters are the record's state, and the generated constructor assigns them. To check or normalise them first, write a compact constructor: a constructor with no parameter list, whose body runs before the fields are assigned.

Money.java
public record Money(BigDecimal amount, String currency) {
    public Money {
        Objects.requireNonNull(amount, "amount");
        if (currency == null || currency.length() != 3) {
            throw new IllegalArgumentException("currency must be a 3-letter ISO code: " + currency);
        }
        amount = amount.setScale(2, RoundingMode.HALF_EVEN);
        currency = currency.toUpperCase(Locale.ROOT);
    }

    public static Money of(String amount, String currency) {
        return new Money(new BigDecimal(amount), currency);
    }

    public Money plus(Money other) {
        if (!currency.equals(other.currency)) {
            throw new IllegalArgumentException("currency mismatch");
        }
        return new Money(amount.add(other.amount), currency);
    }
}

Inside the compact constructor, amount and currency are the parameters, and reassigning them changes what gets stored. You never write this.amount = amount; the compiler adds the assignments at the end. Money.of("19.9", "eur").plus(Money.of("0.1", "EUR")) gives Money[amount=20.00, currency=EUR].

As the example shows, records can have static factory methods and ordinary instance methods. They can also implement interfaces and have static fields. What they cannot have is extra instance fields: all state lives in the header.

Extra constructors

You can add other constructors, but each must delegate to the canonical one with this(...):

Java
public record Range(int start, int end) {
    public Range {
        if (start > end) throw new IllegalArgumentException(start + " > " + end);
    }

    public Range(int end) {
        this(0, end);
    }

    public int length() {
        return end - start;
    }
}

Because every path goes through the canonical constructor, the validation runs no matter how a Range is created.

Immutability, and the collection trap

Record fields are final, so a record is shallowly immutable: you cannot reassign a component. If a component is itself mutable, such as a List, the caller can still change it from outside:

Java
public record Order(String id, List<String> items) {
    public Order {
        items = List.copyOf(items);
    }
}

Without the List.copyOf line, code that kept a reference to the original list could add items after the order was created, and order.items().add(...) would modify the record from the outside. List.copyOf makes an unmodifiable copy (and rejects null elements), so the record's state is fixed once constructed. The same applies to arrays, Date and any other mutable type: copy in the constructor.

To "change" a record, return a new one. A with method per field is the usual pattern:

Java
public record Person(String name, int age) {
    public Person withAge(int newAge) {
        return new Person(name, newAge);
    }
}

Local records for intermediate results

A record can be declared inside a method, which is handy for naming the intermediate values of a stream pipeline instead of using Map.Entry or Object[]:

Java
record Total(String customer, BigDecimal sum) {}

List<Total> totals = byCustomer.entrySet().stream()
        .map(e -> new Total(e.getKey(), e.getValue()))
        .sorted(Comparator.comparing(Total::sum).reversed())
        .toList();

Local records are implicitly static, so they cannot capture local variables from the enclosing method.

Record patterns in Java 21

Java 16 already let you test and cast in one step with instanceof Point p. Java 21 (JEP 440) lets the pattern take the record apart into its components:

Java
static String describe(Object obj) {
    if (obj instanceof Point(int x, int y) && x == y) {
        return "on the diagonal at " + x;
    }
    return "something else";
}

The real payoff is in switch, combined with sealed interfaces, where the compiler checks that every case is handled:

Shapes.java
record Point(int x, int y) {}
sealed interface Shape permits Circle, Rectangle, Line {}
record Circle(Point centre, double radius) implements Shape {}
record Rectangle(Point topLeft, Point bottomRight) implements Shape {}
record Line(Point from, Point to) implements Shape {}

static double area(Shape shape) {
    return switch (shape) {
        case Circle(Point centre, double r) -> Math.PI * r * r;
        case Rectangle(Point(int x1, int y1), Point(int x2, int y2)) -> Math.abs((x2 - x1) * (y2 - y1));
        case Line l -> 0;
    };
}

Patterns nest, so Rectangle(Point(int x1, int y1), ...) reaches two levels into the data in one case. There is no default branch: because Shape is sealed, the compiler knows these three cases are complete, and adding a fourth shape later turns every incomplete switch into a compile error instead of a runtime surprise. You can write var instead of a component's type, and from Java 22 an unused component can be written as _. The Java 21 features tutorial covers pattern matching for switch in more depth.

Records with JSON, JPA and other frameworks

  • Jackson has supported records since version 2.12: it serializes the components and deserializes through the canonical constructor, so the compact constructor's validation runs on incoming JSON.
  • Spring Boot can bind @ConfigurationProperties to a record, which gives you immutable, validated configuration.
  • JPA entities cannot be records. An entity needs a no-argument constructor and mutable state that the persistence provider can set and proxy. Records work well for query results and DTOs instead, for example as the result type of a JPQL constructor expression.
  • Java serialization handles records specially: it always uses the canonical constructor, so the validation also runs on deserialized data.

When a record is the wrong tool

A record is a good fit when the data is the identity: two Money values with the same amount and currency are the same money. It is a poor fit when an object has identity beyond its data (two customers with the same name are different customers), when it needs mutable state, or when it must extend another class, since records implicitly extend java.lang.Record. In those cases write a normal class. Libraries such as Lombok's @Value produced similar classes before records existed; for new code on Java 17 or newer the built-in record does the same job without an annotation processor.

Records also show up across this site's other tutorials: the Order rows in the Apache POI tutorial and the payload in the AES encryption tutorial are both records. The language definition is JEP 395, and record patterns are JEP 440.

About Glenna Babshire29 Articles
Java & libraries writer. Writes the Java tutorials: the language from Java 21 on, encryption, configuration and the libraries around it.