Skip to content
AgileLogics
4 min read

Records

Prerequisites: Concurrency in depth

A record (Java 16+) is a compact, immutable data carrier — the compiler generates the constructor, accessors, equals, hashCode, and toString automatically from the field list.

record Point(int x, int y) {}

Point p = new Point(3, 4);
System.out.println(p.x());       // 3 — accessor, not getX()
System.out.println(p);            // Point[x=3, y=4]
System.out.println(p.equals(new Point(3, 4))); // true

Compare that to the equivalent hand-written class, which used to take 30+ lines for the same guarantees. A record can still add its own methods and validation in a compact constructor:

record Range(int min, int max) {
    Range {
        if (min > max) {
            throw new IllegalArgumentException("min must be <= max");
        }
    }
}

Common mistakes

  • Trying to add a mutable setter to a record — records are intentionally immutable; if a field needs to change, it isn't a good fit for a record.