Java Records: Compact Data Classes with Canonical and Compact Constructors
Java records explained: declaring immutable data carriers in one line, components and accessors like x(), generated toString, equals and hashCode, adding methods and static members, canonical, compact and custom constructors for validation and normalization, and when to choose a record over a class.
kvi5hnuCode Sprout team member9 min readOn this page
Encapsulation earns its keep when a class has internal details worth protecting. Some classes don't. Think of a colour made of red, green and blue intensities:
class Rgb {
private final int red;
private final int green;
private final int blue;
public Rgb(int red, int green, int blue) { this.red = red; this.green = green; this.blue = blue; }
public int getRed() { return red; }
public int getGreen() { return green; }
public int getBlue() { return blue; }
public String toString() { return "Rgb[red=" + red + ", green=" + green + ", blue=" + blue + "]"; }
// ...plus equals and hashCode, written by hand
}
What would the private fields protect here? The three numbers are the colour. Nobody will ever swap the representation for something else behind the getters, so the class is twenty lines of ceremony around three values.
That is the situation records were designed for. They appeared as a preview in Java 14 and became a standard feature in Java 16.
The Record Concept
A record is a class whose entire state is a fixed list of values, fixed at construction and readable by anyone. The declaration names the record and lists those values:
record Rgb(int red, int green, int blue) { }
From that header the compiler produces:
| Generated member | For Rgb |
|---|---|
A private final field per component (the JLS term for the header variables) | red, green, blue |
| The canonical constructor, taking every component in order | Rgb(int red, int green, int blue) |
| A public accessor per component, named exactly like it | red(), green(), blue() |
toString, equals, hashCode computed from the components | Rgb[red=255, green=128, blue=0] |

var orange = new Rgb(255, 128, 0);
System.out.println(orange.green()); // 128
System.out.println(orange); // Rgb[red=255, green=128, blue=0]
System.out.println(orange.equals(new Rgb(255, 128, 0))); // true: same components
The accessor is green(), not getGreen(). A class may have a field and a method with the same name, so this is legal.
The inheritance part explains toString, equals and hashCode in depth. In short: toString describes the record, equals compares two records component by component, and hashCode agrees with equals, so records behave correctly in HashSets and as HashMap keys.
Adding Methods and Static Members
The body of a record may declare methods:
record Rgb(int red, int green, int blue) {
public int brightness() {
return (red + green + blue) / 3;
}
}
Static fields and methods are allowed too:
record Rgb(int red, int green, int blue) {
public static final Rgb BLACK = new Rgb(0, 0, 0);
public static Rgb mix(Rgb a, Rgb b) {
return new Rgb((a.red + b.red) / 2, (a.green + b.green) / 2, (a.blue + b.blue) / 2);
}
}
You may also replace a generated method with your own, as long as the signature matches:
record Rgb(int red, int green, int blue) {
public int red() { return 255 - red; } // compiles, but now red() lies about the component
}
Doing that to an accessor is a bad idea, since everyone expects red() to return the component. Replacing toString, for example to mask a secret component, is a legitimate use.
Something you can't add is another instance field. The components are the whole state:
record Rgb(int red, int green, int blue) {
private String label; // error: field declaration must be static
}
The remaining limits come from the same idea:
- The fields are final. There are no setters and no way to reassign a field after construction.
- A record is implicitly final, so nothing can extend it, and it can't extend anything itself, because it already extends
java.lang.Record. Implementing interfaces is fine.
Final fields, mutable objects
final stops a field from pointing somewhere else. It doesn't stop the object it points to from changing:
record Booking(String guest, Date checkIn) { }
var b = new Booking("Mina", new Date());
b.checkIn().setTime(0); // the booking's date just changed
Booking is therefore not really immutable. Immutable records need immutable component types: LocalDate or Instant rather than Date, and an unmodifiable copy (List.copyOf) rather than the caller's ArrayList, as the compact-constructor example below shows.
Constructors: Canonical, Compact and Custom
The canonical constructor
The constructor the compiler generates, the one that receives every component, is the canonical constructor.
Compact constructors: validate and normalize
To check or adjust the arguments before the fields are set, write a compact constructor. It is the record name followed directly by a body, with no parameter list:
record Rgb(int red, int green, int blue) {
public Rgb { // compact form: rejecting bad input
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255)
throw new IllegalArgumentException("channel out of range");
}
}
Instead of rejecting, a compact constructor can also normalize:
record Percent(double value) {
public Percent { // compact form: clamping the parameter
value = Math.max(0, Math.min(100, value));
}
}
Think of the compact body as code that runs at the start of the canonical constructor. It sees the parameters (value) and may assign new values to them. When it ends, each field is set from the matching parameter, including any changes. The fields themselves are off-limits in the body: this.value = value; there fails with "cannot assign a value to final variable value".
Compact constructors are the idiomatic place for defensive copies of mutable inputs:
record Article(String title, List<String> tags) {
public Article {
Objects.requireNonNull(title);
tags = List.copyOf(tags); // immutable copy: callers can't change our list later
}
}
Custom constructors
A record can have additional constructors. Each must call another constructor with this(...), so that every path ends in the canonical constructor. (Since Java 25 you may put statements such as argument checks before the this(...) call, just as in any class; see the previous article.)
record Rgb(int red, int green, int blue) {
public Rgb(int gray) { this(gray, gray, gray); } // a shade of gray
}
new Rgb(200) now produces Rgb[red=200, green=200, blue=200]. Static factory methods (Rgb.ofHex("#FF8000"), say) are the other common way to offer alternative ways to create a record, and they can have descriptive names.
Writing the canonical constructor yourself
You may also spell out the full canonical constructor, assigning every field. It is legal but rarely worth it, since the compact form does the same job with less code:
record Percent(double value) {
public Percent(double value) { // legal, but wordier than the compact form
this.value = Math.max(0, Math.min(100, value));
}
}
A Complete Example
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Solution {
public static void main(String[] args) {
var orange = new Rgb(255, 128, 0);
System.out.println("green of orange: " + orange.green());
System.out.println("brightness: " + orange.brightness());
System.out.println("mixed with black: " + Rgb.mix(orange, Rgb.BLACK));
System.out.println(orange + " " + orange.equals(new Rgb(255, 128, 0)));
System.out.println(new Rgb(200));
try {
new Rgb(300, 0, 0);
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
// a record that is not really immutable
var b = new Booking("Mina", new Date(86_400_000));
System.out.println("check-in before: " + b.checkIn().getTime());
b.checkIn().setTime(0);
System.out.println("check-in after: " + b.checkIn().getTime());
// normalizing compact constructor
System.out.println(new Percent(130) + " " + new Percent(-5) + " " + new Percent(42.5));
// defensive copy in a compact constructor
var tags = new ArrayList<>(List.of("java"));
var article = new Article("Records", tags);
tags.add("oops");
System.out.println(article.tags());
}
}
record Rgb(int red, int green, int blue) {
// a static field
public static final Rgb BLACK = new Rgb(0);
// a compact constructor that validates
public Rgb {
if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255)
throw new IllegalArgumentException("channel out of range: " + red + "," + green + "," + blue);
}
// a custom constructor
public Rgb(int gray) {
this(gray, gray, gray);
}
// a method
public int brightness() {
return (red + green + blue) / 3;
}
// a static method
public static Rgb mix(Rgb a, Rgb b) {
return new Rgb((a.red + b.red) / 2, (a.green + b.green) / 2, (a.blue + b.blue) / 2);
}
}
record Booking(String guest, Date checkIn) { }
record Percent(double value) {
// a compact constructor that normalizes
public Percent {
value = Math.max(0, Math.min(100, value));
}
}
record Article(String title, List<String> tags) {
public Article {
tags = List.copyOf(tags);
}
}
green of orange: 128
brightness: 127
mixed with black: Rgb[red=127, green=64, blue=0]
Rgb[red=255, green=128, blue=0] true
Rgb[red=200, green=200, blue=200]
rejected: channel out of range: 300,0,0
check-in before: 86400000
check-in after: 0
Percent[value=100.0] Percent[value=0.0] Percent[value=42.5]
[java]
Records in Modern Java
Records combine with other modern features:
- Local records: you can declare a record inside a method, which is ideal for intermediate results (
record Pair(String key, int count) {}). - Record patterns (Java 21):
if (obj instanceof Rgb(int r, int g, int b))tests the type and extracts the components in one step. They work inswitchtoo. Pattern matching is covered in the inheritance part. - Records are a natural fit for DTOs (data transfer objects), API responses, map keys, multiple return values, and value objects like
Money(BigDecimal amount, Currency currency).
Record or Class?
| Record | Class | |
|---|---|---|
| Fields | exactly the components, all final | anything |
Constructor, accessors, equals/hashCode/toString | generated | written by you (or generated by the IDE) |
| Mutability | immutable (if components are) | your choice |
| Inheritance | can't extend classes, is final; can implement interfaces | can extend and be extended |
| Hides representation | no: the components are the API | yes |
Before records, libraries like Lombok (@Value, @Data) or IDE code generation filled this gap. Records make that boilerplate unnecessary for immutable data.
Common questions
Do records compare array components by content?
No. The generated equals uses equals for reference components, and arrays inherit identity-based equals from Object. So two records with equal-looking int[] components aren't equal. Use a List component instead, or override equals, hashCode and toString yourself.
How do records compare double components?
They use the Double.compare rules, not ==. A record holding NaN therefore equals another record holding NaN, and a record holding 0.0 does not equal one holding -0.0. This keeps equals consistent with hashCode for records used as map keys.
Can I use records with JPA or other frameworks? Jackson, Spring and most modern libraries handle records well. They are a good fit for DTOs and query results. JPA entities can't be records, because entities need to be mutable, need a no-argument constructor, and are often proxied by subclasses. Records work fine as JPA projections and embeddable values in recent versions.
Can a record have a "wither" like withRed(...)?
Yes, write it yourself: Rgb withRed(int r) { return new Rgb(r, green, blue); }. A language feature for derived record creation (color with { red = 0; }) has been proposed (JEP 468), but no release up to Java 27 includes it.
Are records serializable?
Only if they implement Serializable, like any class. Record serialization is safer than ordinary class serialization: deserialization always goes through the canonical constructor, so the validation in your compact constructor runs for deserialized objects as well.
Summary
record Name(Type a, Type b) { }declares a final class with private final fields, a canonical constructor, accessorsa()andb(), and component-basedtoString,equalsandhashCode.- Records can have methods, static fields and static methods, and can implement interfaces. They can't declare instance fields or extend classes.
- Use a compact constructor (
public Name { … }) to validate or normalize parameters, and to make defensive copies. Assign to the parameters, not the fields. - Custom constructors must delegate with
this(...)(Java 25 allows validation statements before it). An explicit canonical constructor is legal but rarely needed. - Keep components immutable; a
finalreference to a mutable object makes the record mutable. - Prefer records for plain immutable data, and classes when you need mutability or encapsulation.
Practice Questions
What members does record Book(String title, int pages) {} have?
Private final fields title and pages; a canonical constructor Book(String title, int pages); public accessors title() and pages(); and toString, equals, hashCode based on both components. It's implicitly final and extends java.lang.Record.
Write a record Temperature(double celsius) that rejects values below absolute zero (−273.15).
record Temperature(double celsius) {
public Temperature {
if (celsius < -273.15) {
throw new IllegalArgumentException("Below absolute zero: " + celsius);
}
}
}
Why doesn't this compile? record Account(String id) { private double balance; }
Records can't declare instance fields beyond their components. Their state is exactly the components. Either add balance as a component (making it immutable), or use a regular class if the balance needs to change.
record Team(String name, List<String> members) {}. A caller passes an ArrayList and later adds a member to it. Does the record change? How do you prevent it?
Yes. The record holds a reference to the caller's mutable list. Make a defensive, immutable copy in a compact constructor: public Team { members = List.copyOf(members); }.
Is new Point(1, 2).equals(new Point(1, 2)) true for record Point(int x, int y) {}? Would it be for an ordinary class without an equals method?
Yes for the record: generated equals compares components. For an ordinary class without its own equals, it would be false, because the inherited Object.equals compares identity.
Previous: Java Object Construction: Overloading, Default Fields, this(), and Initialization Blocks
Next: Java Packages: Package Names, Imports and Static Imports
Related reading
- Java static Fields and Methods: Class Variables, Constants, Factory Methods and main
- Defining Your Own Classes in Java: Fields, Constructors and Methods
- Using Predefined Classes in Java: Objects, Object Variables and LocalDate
- Introduction to Object-Oriented Programming in Java
- Java Arrays: Sorting, the Arrays Class, Multidimensional and Ragged Arrays

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.