Records
A record is a class whose whole state is a short list of components, and whose constructor, accessors, equals, hashCode and toString the compiler writes from that list. It is final, its fields are private and final, and it exists so that a value such as a coordinate, a range or an amount is declared in one line instead of forty, with no chance that the equals and hashCode disagree. Records are final in Java 16 and this course uses them from Java 21.
A record declaration
One line declares the type, its two components, and a constructor that takes them in that order. The record below is the Point of lesson 053 written the modern way:
public class Points {
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println(a);
System.out.println(a.x() + " " + a.y());
System.out.println(a.equals(b));
System.out.println(a.hashCode() == b.hashCode());
System.out.println(a instanceof Point);
}
}
record Point(int x, int y) {
}
javac -Xlint:all Points.java
java Points
Point[x=1, y=2]
1 2
true
true
true
The accessors are named after the components and take no arguments: x() and y(), not getX(). The two points are equal although they are two objects, because equals compares the components, and their hash codes agree for the same reason.
What the compiler writes
Five members appear from the one-line body, and they are the five a hand-written value class has to write and can get wrong:
A private final field per component. A canonical constructor that assigns them. An accessor per component. An equals that compares the runtime class and every component, and a hashCode built from the same components. A toString of the form Point[x=1, y=2]. The class is final, it extends java.lang.Record, and it declares no other instance fields.
javap prints the members the compiler wrote, which is the shortest proof that they exist:
javap -p -cp out-Points Point
Compiled from "Points.java"
final class Point extends java.lang.Record {
private final int x;
private final int y;
Point(int, int);
public final java.lang.String toString();
public final int hashCode();
public final boolean equals(java.lang.Object);
public int x();
public int y();
}
Those lines were printed by the same JDK from the class file of the run above. -p shows the members whatever their access, so the two private fields appear as well, and the constructor without a return type is the canonical one.
The compact constructor
Validation belongs in the constructor, and a record lets it be written without repeating the parameter list or the assignments. The compact form names no parameters and assigns no fields: the parameters are the components, and the compiler adds the assignments after the body.
public class RangeDemo {
public static void main(String[] args) {
Range range = new Range(1, 5);
System.out.println(range);
System.out.println(range.length());
try {
new Range(5, 1);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}
record Range(int from, int to) {
Range {
if (from > to) {
throw new IllegalArgumentException("from " + from + " > to " + to);
}
}
int length() {
return to - from;
}
}
javac -Xlint:all RangeDemo.java
java RangeDemo
Range[from=1, to=5]
4
from 5 > to 1
The second construction throws before any field is assigned, so no Range with the wrong order can exist. The message carries the two values, which is the exception design of the exceptions part of the course, and the try and catch are the same part.
Methods and factories
A record body may hold instance methods, static methods, static fields and extra constructors that delegate to the canonical one. It may not hold another instance field. The amount below has a factory that takes dollars and cents, an addition and a format:
public class MoneyDemo {
public static void main(String[] args) {
Money price = Money.of(12, 50);
Money tax = new Money(99);
System.out.println(price);
System.out.println(price.plus(tax));
System.out.println(price.plus(tax).format());
System.out.println(price.equals(Money.of(12, 50)));
}
}
record Money(long cents) implements Comparable<Money> {
static Money of(long dollars, long cents) {
return new Money(dollars * 100 + cents);
}
Money plus(Money other) {
return new Money(cents + other.cents);
}
String format() {
return String.format("%d.%02d", cents / 100, cents % 100);
}
@Override
public int compareTo(Money other) {
return Long.compare(cents, other.cents);
}
}
javac -Xlint:all MoneyDemo.java
java MoneyDemo
Money[cents=1250]
Money[cents=1349]
13.49
true
plus returns a new record and leaves both operands alone, which is what a value type does. The factory keeps the two units of money in one place, and Comparable is the ordering interface of lesson 075; the order it gives is the one a sorted list of amounts uses.
A record implements an interface
A record may implement interfaces and may be used wherever a value is wanted. This circle carries its radius, refuses a radius that is not positive, and answers its area; the stream is only a way to call the method twice:
import java.util.List;
public class ShapeDemo {
public static void main(String[] args) {
List<Circle> circles = List.of(new Circle(1.0), new Circle(2.5));
circles.stream()
.map(Circle::area)
.map(a -> String.format("%.2f", a))
.forEach(System.out::println);
System.out.println(circles.get(0));
}
}
record Circle(double radius) implements Comparable<Circle> {
Circle {
if (radius <= 0) {
throw new IllegalArgumentException("radius " + radius);
}
}
double area() {
return Math.PI * radius * radius;
}
@Override
public int compareTo(Circle other) {
return Double.compare(radius, other.radius);
}
}
javac -Xlint:all ShapeDemo.java
java ShapeDemo
3.14
19.63
Circle[radius=1.0]
The lambda and the method reference belong to the functional part of the course; the point here is that a record is an ordinary class in everything but its state, so it fits every place a class fits.
What a record is not
A record cannot extend a class, because it already extends java.lang.Record, and nothing may extend a record. It cannot declare an instance field beyond its components, so a derived value is a method, not a field. It is not mutable: the fields are final, and a component that is an array or a list is a reference to a mutable object, so an immutable record with an array component must copy it in the compact constructor and in the accessor, as lesson 042 shows for a class.
A record also cannot be a bean: it has no setters and no getX names, so a framework that expects them does not accept it. For a value that is built once and read, that is the point.
Exercises
- Add a component to Point and watch every construction on the page stop compiling.
- Give Range a method contains(int) and print the answer for 3 and for 7.
- Write a record Person(String name, int age) with a compact constructor that refuses a negative age, and print a list of two people.
- Try to add an instance field to a record and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which members does the compiler write for a record?
Answer
The canonical constructor, the accessors, equals, hashCode and toString
The component list is the whole state, so all five are derived from it.
-
What is the accessor of a component named
xcalled?Answer
x()
A record names its accessors after the components, without the get prefix.
-
What does a compact constructor do?
Answer
Takes the components as parameters and validates them before the fields are assigned
It is the canonical constructor written without the parameter list, and the compiler adds the assignments after its body.
-
What does this program print?
public class Q1 { public static void main(String[] args) { P p = new P(1, 2); System.out.println(p); } } record P(int a, int b) { }Answer
P[a=1, b=2]
The generated toString names the record and every component.
-
What does this program print?
public class Q2 { public static void main(String[] args) { P a = new P(1, 2); P b = new P(1, 2); System.out.println(a.equals(b)); System.out.println(a == b); } } record P(int a, int b) { }Answer
true then false
equals compares the components, while == compares the two references.
-
What does this program print?
public class Q3 { public static void main(String[] args) { try { new R(3, 1); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } } } record R(int from, int to) { R { if (from > to) { throw new IllegalArgumentException("bad range"); } } int length() { return to - from; } }Answer
bad range
The compact constructor refuses the order before any field is assigned, and the message is the one it threw.
-
What does this program print?
public class Q4 { public static void main(String[] args) { P p = new P("a"); System.out.println(p.name() + p.n()); } } record P(String name) { int n() { return name.length(); } }Answer
a1
The accessor returns the component, and the added method reads it like any other field.
-
What does this program print?
public class Q5 { public static void main(String[] args) { P a = new P(1); P b = new P(2); System.out.println(a.hashCode() == b.hashCode()); System.out.println(new P(2).equals(b)); } } record P(int v) { }Answer
false then true
Different values usually hash differently, and the two objects with value 2 are equal.
-
Why can a record not declare an instance field of its own?
Answer
Its state is exactly its component list, and the generated methods depend on that
equals, hashCode and toString are generated from the components, so another field would be invisible to them.
-
What is true of a record with an array component?
Answer
The component is a reference to a mutable array, so a copy is needed for immutability
A record field is final, but the object it refers to can still be changed through the reference.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev