Records
Declare immutable data carriers in one line, with equals, hashCode and toString included.
Open this lesson in the learning hubKey points
- A
recorddeclares data in one line:record Point(int x, int y) {}. - You get the constructor, accessors,
equals,hashCodeandtoStringfor free. - Accessors are named
x(), notgetX(), and the fields arefinal— a record never changes after construction. - The compact constructor
Point { ... }validates or normalises the arguments before the fields are assigned. - Records can add methods and static factories, but cannot extend a class. They are implicitly final.
- Ideal for DTOs, map keys and multi-value returns. Not a replacement for classes with real behaviour.
Example
import java.util.List;
public class Main {
record Point(int x, int y) {
Point {
if (x < 0 || y < 0) throw new IllegalArgumentException("negative: " + x + "," + y);
}
double distanceFromOrigin() { return Math.sqrt(x * x + y * y); }
static Point origin() { return new Point(0, 0); }
}
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println("toString for free: " + p);
System.out.println("accessor p.x() = " + p.x() + ", distance = " + p.distanceFromOrigin());
System.out.println("equals by value: " + p.equals(new Point(3, 4)));
System.out.println("same hashCode: " + (p.hashCode() == new Point(3, 4).hashCode()));
System.out.println("static factory: " + Point.origin());
System.out.println("in a list: " + List.of(p, new Point(1, 1)));
try {
new Point(-1, 0);
} catch (IllegalArgumentException e) {
System.out.println("compact constructor validated: " + e.getMessage());
}
}
}
Records give value semantics for free — use them for plain data.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.