5 · Intermediate · lesson 27 of 41

Records

Immutable data carriers with equals/hashCode/toString for free (Java 14+).

Java
record Point(double x, double y) {
    // compact constructor — validation
    public Point {
        if (Double.isNaN(x) || Double.isNaN(y))
            throw new IllegalArgumentException();
    }
    double distance(Point o) {
        return Math.hypot(x - o.x, y - o.y);
    }
}
Key takeaways
  • ✓Records are implicitly final and immutable.
  • ✓Fields become accessor methods: p.x() not p.x.