Articles Java

Java record vs class: when to use which

Use a record when a type is nothing more than its data: a fixed set of values that are set once and compared by value. Use a class when the object has identity, changes over time, hides its state, or has to take part in inheritance. A record is still a class, only a restricted one, and those restrictions are the reason to pick it.

Records have been a standard part of the language since Java 16 (JEP 395), so everything below works the same on Java 21 and 25.

What does a Java record give you for free?

One line declares the whole type:

record Point(int x, int y) {}

From that header the compiler generates a private final field per component, a constructor taking all components (the canonical constructor), an accessor per component, and equals, hashCode and toString based on every component.

Point a = new Point(2, 3);
Point b = new Point(2, 3);

System.out.println(a);
System.out.println(a.x());
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
Point[x=2, y=3]
2
true
true

Two details surprise people coming from JavaBeans. The accessor is x(), not getX(). And the toString format is not a contract: the Javadoc of Record says it may change, so never parse it.

The equivalent class takes around thirty lines, and its real cost comes later. Add a field to a hand-written class and forget to update equals, and you have a bug no compiler reports. A record cannot get out of sync with its own components.

What can a record not do that a class can?

The restrictions are short enough to memorise:

  • No extends. Every record already extends java.lang.Record. It can implement interfaces.
  • Nobody can extend it. A record is implicitly final and cannot be abstract.
  • Fields are final. There are no setters to write, because assignment does not compile.
  • No extra instance state. Any field you declare in the body must be static.

The compiler is clear about each of these. Declaring an instance field in the body gives:

error: field declaration must be static
    private int cachedHash;
                ^
  (consider replacing field with record component)

Everything else is allowed: instance and static methods, static fields, additional constructors (they must delegate to the canonical one with this(...)), nested types and generics.

The rule behind all four limits is that the header is the complete description of the state. If you find yourself wanting a hidden field, a lazily computed cache or a base class, the type is not plain data and should be a class.

How do you validate a record? The compact constructor

A record does not force you to accept any values. The compact constructor has no parameter list and runs before the fields are assigned:

record Range(int from, int to) {
    Range {
        if (from > to) {
            throw new IllegalArgumentException(
                    "from (" + from + ") must not be greater than to (" + to + ")");
        }
    }
}

new Range(5, 1) now fails with IllegalArgumentException: from (5) must not be greater than to (1), and since every other constructor has to go through the canonical one, there is no way around the check.

The same block can normalise input. Inside it you reassign the parameter, not the field, and the compiler copies the parameters into the fields when the block ends:

record Email(String value) {
    Email {
        value = value.strip().toLowerCase();
    }
}

new Email(" [email protected] ") prints as Email[[email protected]]. Writing this.value = ... in a compact constructor is a compile error.

Are Java records immutable? Only shallowly

The Javadoc calls a record “a shallowly immutable, transparent carrier for a fixed set of values”. Shallowly is the important word. The fields cannot be reassigned, but the objects they point to can still change:

record Order(String id, List<String> items) {}

List<String> items = new ArrayList<>(List.of("keyboard"));
Order order = new Order("A-1", items);

items.add("mouse");
order.items().add("monitor");

System.out.println(order);
Order[id=A-1, items=[keyboard, mouse, monitor]]

Both the caller who kept the original list and anyone who calls the accessor can modify the “immutable” order. The fix is a defensive copy in the compact constructor:

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

List.copyOf returns an unmodifiable list that is detached from the source, so later changes to the original list do not reach the record, and order.items().add(...) throws UnsupportedOperationException. It also rejects a null list and null elements, which is usually what you want.

Arrays are the other trap. A record compares reference components with Objects.equals, and two arrays with the same content are not equal that way, so two records holding new int[] {1, 2} are not equal either. Prefer a List component over an array.

Can a record be a JPA entity, a DTO or a Jackson type?

JPA entity: no. The Jakarta Persistence 3.2 specification requires an entity class to have a no-argument constructor and to be non-final, with non-final persistent fields, and it states outright that a record may not be designated as an entity. An entity is also the opposite of a record in spirit: it has identity and a lifecycle, and its state changes while the persistence provider tracks it. Keep entities as classes. The same specification does allow a record as an embeddable class and as a primary key class.

DTO: yes, this is the best use of records. Request and response bodies, query projections, events, configuration values and method results with more than one value are all plain data that crosses a boundary. A JPQL constructor expression such as select new com.example.UserSummary(u.id, u.email) from User u only needs a matching constructor, which a record has by definition.

Jackson: yes, without annotations. Jackson has supported records since version 2.12. It reads JSON through the canonical constructor and writes it through the accessors:

record CreateUserRequest(String email, String displayName) {}

ObjectMapper mapper = new ObjectMapper();
CreateUserRequest request = mapper.readValue(
        "{\"email\":\"[email protected]\",\"displayName\":\"Ada\"}",
        CreateUserRequest.class);

System.out.println(mapper.writeValueAsString(request));
{"email":"[email protected]","displayName":"Ada"}

Because deserialisation goes through the constructor, the validation in your compact constructor runs for incoming JSON as well. A class with setters gives you no such guarantee.

Records and pattern matching

Since Java 21 a record can be taken apart in a switch (JEP 440). Together with a sealed interface, the compiler checks that every case is handled, with no default branch:

sealed interface Shape permits Circle, Rectangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}

static double area(Shape shape) {
    return switch (shape) {
        case Circle(double radius) -> Math.PI * radius * radius;
        case Rectangle(double width, double height) -> width * height;
    };
}

A regular class cannot be deconstructed like this. If you model a closed set of alternatives, that alone is a reason to choose records.

Record or class: a short decision rule

Ask these in order and stop at the first yes:

  1. Does the object change after it is created, or does a framework need to change it (a JPA entity)? Use a class.
  2. Does it need to extend another class, or be extended? Use a class.
  3. Does it hold state that callers must not see, such as a cache, a lock or a connection? Use a class.
  4. Are two instances with the same values still different things, like two user accounts? Use a class.
  5. None of the above? Use a record.

Summary

RecordClass
StateExactly the components in the headerAny fields you declare
FieldsPrivate and finalYour choice
InheritanceImplements interfaces only, implicitly finalFull
equals, hashCode, toStringGenerated from all componentsWritten by you
ValidationCompact constructor, cannot be bypassedEvery constructor and setter
Good forDTOs, value objects, keys, events, projectionsEntities, services, mutable or encapsulated state

Default to a record for data and reach for a class when you need something a record forbids. Remember that the immutability is shallow, so copy collections in the compact constructor, and keep records out of your entity model.