Java Records: What a record Is and How to Use It
A record in Java is a special kind of class for immutable data carriers. You list the components in the header, and the compiler generates private final fields, accessor methods, a canonical constructor, and equals(), hashCode() and toString(). Records became a standard language feature in Java 16 (JEP 395) after two preview rounds in Java 14 and 15.
public record Point(int x, int y) { }
Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
System.out.println(p1); // Point[x=1, y=2]
System.out.println(p1.x()); // 1
System.out.println(p1 == p2); // false — two different objects
System.out.println(p1.equals(p2)); // true — every component is equal That one line replaces a class of roughly forty lines. The price is a set of strict rules: you can't extend a record, you can't declare a regular instance field in it, and a compact constructor can't write this.x = x. OCP exam questions and interview questions are built on exactly these rules, so every one of them below comes with the exact javac error message.
What a record is and what the compiler generates
A record is a final class that implicitly extends java.lang.Record and is fully described by its list of components. From the header record Point(int x, int y) the compiler generates two private final fields, the methods x() and y(), the constructor Point(int x, int y), and implementations of equals(), hashCode() and toString() based on all components.
Written as a regular class, the same thing looks roughly like this:
public final class Point { // a record is implicitly final
private final int x; // one field per component
private final int y;
public Point(int x, int y) { // canonical constructor
this.x = x;
this.y = y;
}
public int x() { return x; } // accessors — no get prefix
public int y() { return y; }
@Override
public boolean equals(Object o) {
return o instanceof Point other && x == other.x && y == other.y;
}
@Override
public int hashCode() { return 31 * Integer.hashCode(x) + Integer.hashCode(y); }
@Override
public String toString() { return "Point[x=" + x + ", y=" + y + "]"; }
} This is a behavioral equivalent, not the literal compiler output. A real record extends java.lang.Record, and its equals(), hashCode() and toString() are implemented in bytecode through invokedynamic and java.lang.runtime.ObjectMethods. You can't extend Record by hand: class P extends Record fails with classes cannot directly extend Record.
| Generated member | What it looks like for record Point(int x, int y) | Can you declare it yourself? |
|---|---|---|
| Fields | private final int x; private final int y; | No. Extra instance fields are forbidden; only static fields are allowed |
| Accessors | public int x(), public int y() | Yes, with the same name, the same type and public |
| Canonical constructor | Point(int x, int y) | Yes, in full or compact form |
equals() and hashCode() | Comparison and hash over all components | Yes, as a normal override |
toString() | Point[x=1, y=2] | Yes |
Superclass and final | extends java.lang.Record, the class is final | No: neither extends nor abstract is allowed |
Record components: fields and accessors
A record component is a type-and-name pair in the record header. Each component gets a private final field with the same name and a public accessor method without the get prefix: for the component title the accessor is title(), not getTitle().
public record Book(String title, int pages) { }
Book book = new Book("Effective Java", 412);
System.out.println(book.title()); // Effective Java
System.out.println(book.pages()); // 412
book.getTitle(); // compile error: cannot find symbol You can declare an accessor explicitly, for example to return a defensive copy of an array. It then has to match the generated one: be public, return exactly the same type, take no parameters and declare no throws clause. @Override is allowed on it, even though technically it overrides nothing.
Explicit accessor in record R(int x) | Result |
|---|---|
public int x() { return x; } | Compiles |
int x() { return x; } | invalid accessor method in record R (accessor method must be public) |
public long x() { return x; } | invalid accessor method in record R (return type of accessor method x() must match the type of record component x) |
public int x() throws Exception { return x; } | invalid accessor method in record R (throws clause not allowed for accessor method) |
A few more rules for components:
- A component can't share its name with a no-argument method of
Object:clone,finalize,getClass,hashCode,notify,notifyAll,toString,wait. Forrecord R(int hashCode)javac reportsillegal record component name hashCode. - The last component can be varargs:
record Numbers(int... values). Under the hood it's anint[]field, with all the consequences forequals()described below. - A record can be generic:
record Pair<A, B>(A first, B second). Type parameters are covered in Java Generics. - A record can have no components at all:
record Empty() { }compiles, and itstoString()returnsEmpty[]. - An annotation on a component (
record User(@NotNull String name)) is propagated to the field, the accessor and the constructor parameter — wherever its@Targetallows.
The canonical constructor in Java records
The canonical constructor is the constructor whose parameters match the record components in order, type and name. If you don't declare one, the compiler generates it and simply assigns each parameter to the field with the same name. You can declare it in two forms, full and compact; the full form looks like an ordinary class constructor.
public record Account(String id, long balance) {
public Account(String id, long balance) {
if (balance < 0) {
throw new IllegalArgumentException("balance < 0: " + balance);
}
this.id = id;
this.balance = balance;
}
} In the full form you must assign every field exactly once, just as with any final fields in a constructor. The other rules are record-specific:
| Rule | Violation in record R(int x) | javac error |
|---|---|---|
| Parameter names match component names | R(int y) { this.x = y; } | invalid canonical constructor in record R (invalid parameter names in canonical constructor) |
| Access is not more restrictive than the record's | public record R(int x) { private R(int x) {...} } | invalid canonical constructor in record R (attempting to assign stronger access privileges; was public) |
No throws clause | R(int x) throws Exception {...} | invalid canonical constructor in record R (throws clause not allowed for canonical constructor) |
No this(...) or super(...) call | R(int x) { super(); this.x = x; } | invalid canonical constructor in record R (canonical constructor must not contain explicit constructor invocation) |
| Every field is assigned | R(int x) { } | variable x might not have been initialized |
| And only once | R(int x) { this.x = x; this.x = 2; } | variable x might already have been assigned |
The parameter-name rule looks picky, but there's a reason for it: serialization, reflection (Class.getRecordComponents()) and record patterns all rely on component names, and a constructor R(int y) would break that link. "Not more restrictive" means a public record can only have a public canonical constructor, while a package-private record can use any access level except private.
The compact constructor in Java records
A compact constructor is a shorthand form of the canonical constructor: no parameter list and no field assignments. Its body runs before the compiler copies the parameters into the fields, which makes it the place to validate and normalize arguments. The compiler appends the this.x = x assignments to the end of the body itself.
public record Range(int from, int to) {
public Range { // no parentheses, no parameters
if (from > to) {
throw new IllegalArgumentException("from > to: " + from + " > " + to);
}
} // implicitly: this.from = from; this.to = to;
}
new Range(5, 1);
// Exception in thread "main" java.lang.IllegalArgumentException: from > to: 5 > 1 To normalize a value, assign a new value to the parameter: the field receives the corrected string.
public record Email(String value) {
public Email {
Objects.requireNonNull(value, "value");
value = value.strip().toLowerCase(); // reassign the parameter, not the field
}
}
System.out.println(new Email(" Ann@Mail.COM ")); // Email[value=ann@mail.com] What a compact constructor can't do:
- Assign fields.
public Range { this.from = from; }doesn't compile:cannot assign a value to final variable from. The compiler assigns the field anyway, and a second assignment to afinalfield is illegal. - Use
return. An early exit would skip the implicit assignments. javac reportsinvalid compact constructor in record <init>with the note(compact constructor must not have return statements); the odd<init>instead of the record name is a quirk of the javac message. In the full canonical formreturnis allowed. - Coexist with the full form. Both are the same canonical constructor, so you get
constructor R(int) is already defined in record R.
Which form to use
Almost always the compact one. The full form can't do anything extra apart from an early return, and it's easy to forget a field or mix up names in it. If the constructor neither checks nor changes its arguments, don't declare it at all.
Extra constructors and static factories
Besides the canonical constructor, a record can declare other constructors, but each of them must call another constructor through this(...). Every chain of calls ends in the canonical constructor, so its checks can't be bypassed.
public record Person(String name, int age) {
public Person(String name) {
this(name, 0); // required: delegate to the canonical constructor
}
}
System.out.println(new Person("Ann")); // Person[name=Ann, age=0] Without this(...) the constructor doesn't compile: constructor is not canonical, so it must invoke another constructor of class Person. Before Java 25 the this(...) call had to be the first statement. Java 25 flexible constructor bodies (JEP 513) allow code before it, as long as that code doesn't touch the object under construction:
public record Size(int value) {
public Size(String text) {
int parsed = Integer.parseInt(text.strip()); // Java 25: code before this(...)
this(parsed);
}
}
// On Java 21: error: flexible constructors is not supported in -source 21 A static factory method with a clear name and a static constant are often handier than extra constructors. Static fields and methods are allowed in records — more in Static methods in records.
public record Point(int x, int y) {
public static final Point ORIGIN = new Point(0, 0);
public static Point of(int x, int y) {
return new Point(x, y);
}
public double distanceTo(Point other) { // a regular instance method
return Math.hypot(x - other.x, y - other.y);
}
}
System.out.println(Point.of(3, 4).distanceTo(Point.ORIGIN)); // 5.0 equals(), hashCode() and toString() in Java records
The generated equals() treats two records as equal when they belong to the same record class and all their components are pairwise equal. Reference components are compared with Objects.equals(), primitive ones with the wrapper class's compare(). hashCode() is derived from the hash codes of all components, and toString() prints the record name and the components in square brackets.
Point p1 = new Point(1, 2);
Point p2 = new Point(1, 2);
System.out.println(p1.equals(p2)); // true
System.out.println(p1.hashCode() == p2.hashCode()); // true
System.out.println(p1); // Point[x=1, y=2] The equals()/hashCode() contract holds automatically: equal records always have the same hash code. How that contract works and why breaking it hurts is explained in equals() and hashCode(). The exact hashing algorithm and the exact toString() format are not specified, so don't store a record's hash code in a database or parse its toString() output with a regex.
The wrapper-and-Objects.equals() rule produces a few surprising results:
| Component type | How it's compared | Surprising consequence |
|---|---|---|
int, long, char, boolean | Integer.compare(a, b) == 0 and friends | None: same result as == |
double, float | Double.compare(a, b) == 0 | NaN equals NaN, while 0.0 doesn't equal -0.0 — the exact opposite of == |
String, List, another record | Objects.equals(a, b) | null-safe; lists are compared by content |
| Array | Objects.equals(a, b), i.e. by reference | Two arrays with the same content are not equal, and toString() prints something like [I@1b6d3586 |
record D(double v) { }
record Arr(int[] data) { }
System.out.println(new D(Double.NaN).equals(new D(Double.NaN))); // true (but Double.NaN == Double.NaN is false)
System.out.println(new D(0.0).equals(new D(-0.0))); // false (but 0.0 == -0.0 is true)
System.out.println(new Arr(new int[]{1, 2}).equals(new Arr(new int[]{1, 2}))); // false If a record needs an array that should be compared by content, override equals() and hashCode() with Arrays.equals() and Arrays.hashCode(), or store an immutable List instead.
What does this print? An overridden accessor
record Temperature(double celsius) {
@Override
public double celsius() {
return Math.round(celsius * 10) / 10.0; // round to one decimal place
}
}
Temperature t1 = new Temperature(21.456);
Temperature t2 = new Temperature(21.46);
System.out.println(t1.celsius() + " " + t2.celsius());
System.out.println(t1.equals(t2));
System.out.println(t1); Output:
21.5 21.5
false
Temperature[celsius=21.456] Both accessors return the same value, yet the records aren't equal, and toString() shows the unrounded number. The generated equals(), hashCode() and toString() work with the fields, not the accessors. The fix is simple: normalize data in the compact constructor, and the field, the accessor and all three methods stay consistent.
You rarely need to override the generated methods. A typical case for toString() is hiding a secret that would otherwise end up in the logs:
record Credentials(String login, String password) {
@Override
public String toString() {
return "Credentials[login=" + login + ", password=***]";
}
}
System.out.println(new Credentials("ann", "secret")); // Credentials[login=ann, password=***] How toString() works in regular classes and how the IDE format differs from the record format is covered in the toString() method; when to use getClass() and when instanceof in equals() — in getClass() vs instanceof.
Record restrictions: what you can't declare
A record is implicitly final and already extends java.lang.Record, so it can't extend another class and can't be a superclass. Its state is described only by its components: regular instance fields and instance initializers are forbidden. Static members, instance methods, nested types and interface implementations are allowed.
| Declaration | Allowed? | javac error or comment |
|---|---|---|
record R(int x) extends Base { } | No | '{' expected: the record grammar simply has no slot for extends |
class S extends R { } | No | cannot inherit from final R |
abstract record R(int x) { } | No | modifier abstract not allowed here |
int count; in the record body | No | field declaration must be static (consider replacing field with record component) |
{ ... } — an instance initializer | No | instance initializers not allowed in records |
native void n(); | No | modifier native not allowed here |
void set(int v) { this.x = v; } | No | cannot assign a value to final variable x |
static int count;, static { }, static methods | Yes | Static state isn't part of the components |
Instance methods, main() | Yes | They can read the fields but not change them |
implements Comparable<R> and other interfaces | Yes | Including sealed interfaces |
| Nested classes, interfaces, enums, records | Yes | A nested record is implicitly static |
final record R(int x) { } | Yes | Redundant: a record is already final |
The ban on instance fields is what separates a record from "just a short class". There's no room for a cache, an access counter or a lazily computed field: everything the object stores has to be a component and therefore takes part in equals(). For final classes and inheritance bans in general, see The final keyword.
Records implement interfaces just like regular classes. They pair especially well with sealed interfaces (Java 17): every record is already final, so it can go straight into the permits list.
sealed interface Shape permits Circle, Rect { }
record Circle(double r) implements Shape { }
record Rect(double w, double h) implements Shape { } Records and immutability: mutable components
A record is only shallowly immutable: its fields are final, but if a component refers to a mutable object — an ArrayList, an array, a Date — that object's content can still be changed from outside. To make a record truly immutable, take a defensive copy in the compact constructor.
record BadOrder(String id, List<String> items) { }
record Order(String id, List<String> items) {
Order {
items = List.copyOf(items); // unmodifiable copy
}
}
List<String> source = new ArrayList<>(List.of("tea"));
Order order = new Order("A1", source);
BadOrder bad = new BadOrder("A1", source);
source.add("cake");
System.out.println(order); // Order[id=A1, items=[tea]]
System.out.println(bad); // BadOrder[id=A1, items=[tea, cake]]
order.items().add("x"); // java.lang.UnsupportedOperationException List.copyOf() returns an unmodifiable list and throws NullPointerException if the source contains null; if its argument is already such a list, it doesn't copy it again. An array needs copying twice: clone() in the constructor and in an explicit accessor, otherwise callers get a reference to the internal array. The remaining rules for immutable classes, and how final fields help threads, are in Immutable classes.
Records in collections: HashMap, HashSet, TreeSet
Records make good HashMap keys and HashSet elements: equals() and hashCode() are already consistent and depend only on component values. For TreeSet and TreeMap that's not enough: a record doesn't implement Comparable automatically, so you need a Comparator or your own compareTo().
Set<Point> set = new HashSet<>(List.of(new Point(1, 2), new Point(1, 2), new Point(2, 1)));
System.out.println(set.size()); // 2 — the duplicate is dropped
Map<Point, String> map = new HashMap<>();
map.put(new Point(0, 0), "start");
System.out.println(map.get(new Point(0, 0))); // start — looked up with a new but equal object A record in a TreeSet: ClassCastException
new TreeSet<>(List.of(new Point(2, 1), new Point(1, 2)));
// java.lang.ClassCastException: class Point cannot be cast to class java.lang.Comparable The code compiles; the error appears only when an element is added. There are two fixes: pass a comparator, or declare record Point(int x, int y) implements Comparable<Point>. A comparator built from accessor method references reads best:
TreeSet<Point> sorted = new TreeSet<>(
Comparator.comparingInt(Point::x).thenComparingInt(Point::y));
sorted.addAll(List.of(new Point(2, 1), new Point(1, 5), new Point(1, 2)));
System.out.println(sorted); // [Point[x=1, y=2], Point[x=1, y=5], Point[x=2, y=1]] comparing() and thenComparing() are covered in Comparable and Comparator, the internals of TreeSet in TreeSet in Java.
A composite key instead of concatenated strings
When you need to group by several fields at once, a record replaces keys like region + "|" + product. Such a key can't be assembled incorrectly, and it never collides because of a separator:
record Sale(String region, String product, int amount) { }
record RegionProduct(String region, String product) { }
List<Sale> sales = List.of(
new Sale("EU", "tea", 10), new Sale("EU", "tea", 5),
new Sale("US", "tea", 7), new Sale("EU", "coffee", 3));
Map<RegionProduct, Integer> totals = sales.stream()
.collect(Collectors.groupingBy(
s -> new RegionProduct(s.region(), s.product()),
Collectors.summingInt(Sale::amount)));
System.out.println(totals.get(new RegionProduct("EU", "tea"))); // 15
System.out.println(totals.size()); // 3 Other forms of groupingBy() are covered in Java Collectors class.
A mutable component in a key: the entry gets lost
If a key component is a mutable list, changing it makes the HashMap entry unreachable, even through the very same object:
record Tag(List<String> names) { }
List<String> names = new ArrayList<>(List.of("java"));
Tag key = new Tag(names);
Map<Tag, String> map = new HashMap<>();
map.put(key, "found");
names.add("records"); // key's hash code has changed
System.out.println(map.get(key)); // null
System.out.println(map.get(new Tag(List.of("java")))); // null
System.out.println(map.size()); // 1 — the entry is there but unreachable The entry sits in the bucket computed from the old hash code. A lookup with key goes to a different bucket, and a lookup with the old value finds the bucket but fails equals(). The mechanics are described in Why a mutable key gets lost; the cure is the same List.copyOf() in the compact constructor.
Nested and local records
A nested record is implicitly static: it holds no reference to an outer object and can't see its instance fields. A local record, declared inside a method, is implicitly static too, so unlike a local class it can't access the method's local variables.
class Report {
int limit = 10;
record Line(String text) {
int max() { return limit; } // error: non-static variable limit cannot be referenced from a static context
}
void print(List<String> words) {
int base = 10;
record Stat(String word, int length) {
int score() { return length + base; } // same error for base
}
}
} Local records are handy for intermediate results inside one method, for example in a Stream API pipeline: a type with meaningful field names instead of Map.Entry or an Object[], invisible outside the method. Before Java 16 inner classes couldn't declare static members; JEP 395 lifted that restriction together with introducing records, so a record can be declared even inside an inner class. The kinds of nested classes are compared in Inner classes in Java.
Record patterns in instanceof and switch
Since Java 21 (JEP 440) a record can be taken apart right in a type check: obj instanceof Point(int x, int y) tests the type and declares the variables x and y at once. The same pattern works in switch, together with when guards and nested patterns.
Object obj = new Point(3, 4);
if (obj instanceof Point(int x, int y)) {
System.out.println("x + y = " + (x + y)); // x + y = 7
}
static double area(Shape shape) {
return switch (shape) { // no default needed: Shape is sealed
case Circle(double r) -> Math.PI * r * r;
case Rect(double w, double h) -> w * h;
};
}
System.out.println(area(new Rect(2, 3))); // 6.0 The compiler knows every implementation of the sealed interface Shape, so the switch without default counts as exhaustive. If you later add a third record to permits, this switch stops compiling and points you to the missing branch. Java 22 added unnamed patterns: a component you don't need is replaced with _, as in case Rect(double w, _) when w > 10. The syntax of switch expressions themselves is in Switch-case statement.
Record vs class vs JavaBean vs enum: which to choose
A record fits when an object is fully defined by its data and doesn't change after creation: DTOs, API responses, Map keys, a method result made of several values. If you need mutable state, inheritance or hidden fields, use a regular class; if the set of values is fixed in advance, use an enum.
| Aspect | record | Hand-written immutable class | JavaBean | enum |
|---|---|---|---|---|
| State | Components only, final | Any private final fields | Mutable fields and setters | Fields of the constants |
| Inheritance | No, interfaces only | Usually forbidden (final) | Yes | No, interfaces only |
equals(), hashCode(), toString() | Generated | Written by hand or by the IDE | Written by hand or by the IDE | Identity comparison; toString() is the constant name |
| No-arg constructor | Only for a record with no components | Optional | Required | No: the JVM creates the instances |
| Number of instances | Unlimited | Unlimited | Unlimited | Fixed |
| Typical use | DTOs, keys, tuple-like values | Values with hidden state or a cache | JPA entities, forms, older frameworks | Statuses, types, days of the week |
Lombok's @Value gives a similar result, but it works through annotation processing, while a record is part of the language: the compiler, reflection (Class.isRecord(), getRecordComponents()), serialization and record patterns all understand it. How a record differs from a JavaBean and why Hibernate won't accept it as an entity is covered in Records vs JavaBeans; enums in Enum in Java.
Does it compile? Records in OCP-style questions
The Oracle OCP exam tests records with short snippets: you have to say whether the code compiles and what it prints. Most of these questions come down to the rules in this lesson. Below are the common variants; each result was checked on JDK 25.
| Code | Result | Why |
|---|---|---|
record P(int x) { }new P(1).getX(); | Doesn't compile | The accessor is called x() |
record P(int x) { P { x = Math.abs(x); } }System.out.println(new P(-5)); | P[x=5] | A compact constructor may reassign the parameter |
record P(int x) { P { this.x = x; } } | Doesn't compile | The compiler assigns the field; a second assignment to a final field is illegal |
record P(int x) { P(int x) { if (x < 0) { this.x = 0; return; } this.x = x; } } | Compiles | return is banned only in the compact form |
record P(int x) { static int count; } | Compiles | Static fields are allowed |
record P(int x) { int count; } | Doesn't compile | Instance fields are forbidden |
record P(int x) { P(String s) { System.out.println(s); } } | Doesn't compile | A non-canonical constructor must call this(...) |
record P(int x) { int x() { return x; } } | Doesn't compile | An explicit accessor must be public |
record P(int toString) { } | Doesn't compile | Illegal component name |
new TreeSet<>(List.of(new P(1), new P(2))); | Compiles, ClassCastException | A record doesn't implement Comparable |
Frequently asked questions
Which Java version introduced records?
Records have been a standard feature since Java 16 (JEP 395). In Java 14 and 15 they were a preview feature that needed --enable-preview, and the rules were stricter there: for example, the canonical constructor had to be public. On Java 11 or 8 records aren't available — use a regular class or Lombok @Value. Record patterns in instanceof and switch came later, in Java 21.
Why are record accessors named x() and not getX()?
The authors of JEP 395 deliberately dropped the JavaBeans convention: a record is a transparent data carrier, not a bean with properties. The accessor name matches the component name, and serialization, reflection and record patterns rely on that. Libraries that look for getters added separate support for records: Jackson since version 2.12.
Can a record be a JPA or Hibernate entity?
No. A JPA entity needs a no-arg constructor, mutable fields and the ability to create a proxy subclass, while a record is immutable and final. Records do work well as DTOs and query projections, and Hibernate 6.2+ accepts a record as an @Embeddable. More in Records vs JavaBeans.
How is a record serialized?
Through the usual Serializable, but by its own rules: the component values are written to the stream, and on reading the JVM calls the canonical constructor. So the checks in a compact constructor also run for data coming from the stream, and writeObject() and readObject() are ignored. A worked example is in Record serialization.
Comments