Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Java Record vs Class: When to Use Each

Java records are concise, shallowly immutable data carriers with component-based equality; classes support mutable state, custom equality, and inheritance. This guide explains the practical differences and when each is the better fit.

~8 min readJava
#Java records#Java classes#immutability#data modeling
A visual comparison between a Java record and a Java class, showing a concise record declaration next to a more verbose class definition.

When you declare a Java record, you are telling the compiler that the type's identity is defined entirely by its state. A class, by contrast, leaves that decision to you. This core distinction drives most of the practical differences between the two, and it is the reason choosing between a record and a class depends on how you intend to use the type.

Consider a simple value object that represents a point in a coordinate system. With a class, you write a constructor, getters, equals, hashCode, and toString manually or rely on an IDE to generate them. With a record, the compiler generates all of that from the component list in one line. The record also makes each component a private final field and provides only accessor methods, not setters, so the component values cannot be reassigned after construction. This gives you a shallowly immutable data carrier.

What a Record Changes in Your Data Model

A record is a restricted form of a class designed to hold data as immutable components. Its declaration is concise, but that conciseness is built on strict behavior. Every record has a canonical constructor that takes the same parameters as its components. The compiler also generates equals, hashCode, and toString based on those components.

For example:

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

This single line gives you a class with two final fields, a constructor, accessor methods x() and y(), and value-based equality. The equivalent class would require roughly thirty lines of boilerplate. The record also prevents subclassing: it is implicitly final, and you cannot extend another class because records already extend java.lang.Record.

Syntax Differences Between a Record and a Class

A class gives you full control over the state and behavior. You can have private fields, mutable state, multiple constructors, and inheritance. A record restricts you to a fixed set of components, but you can still add static fields, static methods, and instance methods that do not modify the state.

Here is a class with the same external behavior as the Point record:

java
import java.util.Objects; public final class Point { private final int x; private final int y; public Point(int x, int y) { this.x = x; this.y = y; } public int x() { return x; } public int y() { return y; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Point)) return false; Point p = (Point) o; return x == p.x && y == p.y; } @Override public int hashCode() { return Objects.hash(x, y); } @Override public String toString() { return "Point[x=" + x + ", y=" + y + "]"; } }

The record version is not just shorter; it also guarantees that the equality and hash code behavior are consistent with the components. If you add a component to the record, the generated methods update automatically. In a class, you must remember to update them manually, and forgetting to do so is a common source of bugs.

Equality and Hash Code Behavior

Records use value-based equality: two record instances are equal if all their components are equal. This is the behavior you typically want for data carriers. Classes, unless you override equals and hashCode, use identity equality, which compares object references.

For reference components, the generated methods delegate to the component's own equals and hashCode. This works well when the components are themselves immutable. If a component is mutable, the record's equality and hash code can change after creation, which is risky for use in hashed collections. Also, arrays use reference equality unless you handle them specially, so a record containing an array does not compare the array's contents by default.

This difference matters when you store objects in collections or use them as keys in maps. With a class that does not override equals, two distinct instances with identical field values are not equal. With a record, they are equal by default. If you are building a domain model where two objects should be considered the same because they hold the same data, a record gives you that semantics for free.

However, value-based equality also means that records are not suitable for objects that have identity, such as entities in a database or objects that represent a mutable session. If two instances with the same field values should not be treated as equal, a class with custom equals is the right choice.

When a Record Is Not Enough: Mutable State and Behavior

Records are shallowly immutable. Every component field is final, and component values are set when the object is constructed. If you need to change the state after creation, you cannot use a record. A class allows you to have setters or methods that modify internal fields. Note that if a component references a mutable object, that object can still change, so a record does not automatically give you deeply immutable data.

Consider a class that represents a bank account. The balance changes over time, so the object must be mutable. A record would force you to create a new instance for every transaction, which is possible but often impractical and error-prone. In such cases, a class is the natural fit.

Records also have limitations on behavior. You can add methods that compute values from the components, but you cannot add non-static instance fields that are not part of the component list. If you need to cache a derived value or maintain state outside the component list, a record will not allow it; you would have to compute the value on each call or use a separate class.

Inheritance and Extensibility Constraints

A record is implicitly final. You cannot extend a record, and a record cannot extend any other class. This is a deliberate design choice to preserve the semantics of value-based equality. If you need to model a hierarchy, such as a base Shape class with subclasses Circle and Rectangle, records are not suitable. You would use an abstract class or an interface.

Classes, on the other hand, support inheritance. You can create a base class with common fields and methods and extend it in subclasses. This allows for polymorphism and code reuse. However, inheritance also introduces coupling and can make equality and hash code tricky to implement correctly across a hierarchy. Records avoid this complexity by being final and self-contained.

If you have a closed set of types, you can use a sealed interface with record implementations. Since Java 17, sealed classes and interfaces are available and let you restrict which types can implement them. For example:

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

This gives you the benefits of records (immutability, value equality) while still supporting a limited form of polymorphism.

Performance and Memory Characteristics

Records do not have inherent performance advantages over classes. The generated methods are similar to what you would write manually. The main allocation consideration is that records are immutable, so representing a state change requires creating a new instance; a class can mutate an existing object, avoiding allocation.

Memory usage is similar to an equivalent immutable class. The generated equals and hashCode methods iterate over the components, which is O(n) where n is the number of components.

Records do not have setters, so you cannot accidentally introduce mutable state. A record whose components are immutable is inherently thread-safe, which can reduce the need for defensive copies or synchronization when sharing data across threads. If a component is mutable, however, you still need to protect access to that component.

Choosing Between a Record and a Class for Your Domain Model

The decision between a record and a class comes down to whether the type represents a value or an entity. A value is defined by its data; two values with the same data are interchangeable. An entity has identity; two objects with the same data are not necessarily the same entity.

Use a record when:

  • The object is a simple data carrier, such as a DTO, a response, or a configuration value.
  • The state is effectively immutable, including any objects referenced by the components.
  • You want value-based equality without writing boilerplate.
  • You do not need to extend the type.

Use a class when:

  • The object has mutable state, such as a domain entity that changes over time.
  • You need to control the implementation of equals and hashCode, perhaps to use a business key instead of all fields.
  • You need inheritance or polymorphism.
  • You need non-record instance fields.

There is no universal rule that one is always better. The choice depends on the role the type plays in your application. Records simplify the common case of immutable data carriers, while classes give you the flexibility to model complex behavior and identity.

Compatibility and Migration Considerations

If you are working with an existing codebase, introducing records can change behavior. For example, a class that relied on reference equality will now use value equality if you convert it to a record. This can break code that expects distinct instances to be unequal. Before converting a class to a record, check how instances are compared and used in collections.

Also, records are not compatible with frameworks that rely on no-arg constructors or setters, such as some ORMs or serialization libraries. Java's built-in serialization supports records that implement Serializable, but third-party libraries may require adaptation. If you are using a framework that expects a mutable bean, a record may not be a drop-in replacement.

Finally, records require Java 16 or later. They were previewed in Java 14 and 15 and finalized in Java 16. If your project targets an older Java version, you cannot use records. In that case, you would stick with classes or use a library like Lombok to generate similar boilerplate.

Advanced Record Features: Compact Constructors and Custom Accessors

Records are not completely rigid. You can add a compact constructor to validate or normalize the components before they are assigned. The compact constructor does not have a parameter list; it assigns to the fields implicitly.

java
public record Temperature(double celsius) { public Temperature { if (celsius < -273.15) { throw new IllegalArgumentException("Temperature below absolute zero"); } } }

You can also override the accessor methods to compute a value on the fly, but you cannot add new instance fields. This allows you to keep the immutability guarantee while providing derived data.

These features make records more than a simple data holder. They can encapsulate validation and derived behavior, which reduces the need for a separate class in many cases.

The real question is not which construct is more powerful, but which one matches the semantics you need. Records are a tool for a specific job: immutable data carriers with value equality. Classes are the general-purpose tool for everything else. Choosing the right one makes your code clearer and less error-prone.

Try matching browser tools

All tools

Small utilities that fit Java work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Java guides

More in Java

All Java guides

The guides filed next to this one in Java, in library order.