Records: Data Classes in One Line

A record declares its fields once and gets a constructor, accessors, equals, hashCode and toString for free.

Java · intermediate · 7 min · 25 steps · free

What you'll learn

RecordsDemo.java

record Point(int x, int y) {
    Point {                                  // a compact constructor: checks the values
        if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
    }

    double distanceFromOrigin() {
        return Math.sqrt(x * x + y * y);
    }
}

public class RecordsDemo {
    public static void main(String[] args) {
        Point a = new Point(3, 4);
        Point b = new Point(3, 4);
        int x = a.x();                       // accessors are made for you
        boolean equal = a.equals(b);         // equals compares the values
        double d = a.distanceFromOrigin();
        System.out.println(a + " " + x + " " + equal + " " + d);
    }
}

Step by step

  1. new Point(3, 4) runs the compact constructor, which checks the values.
  2. Line runs: Point { // a compact constructor: checks the values.
  3. Neither value is negative, so no exception.
  4. x in the Point object changes from 0 to 3. y in the Point object changes from 0 to 4.
  5. Point() has finished, so its variables are gone.
  6. a is created on the stack and points to a new Point on the heap: {x: 3, y: 4}.
  7. Java runs the Point constructor to set up the new object, with x = 3 and y = 4.
  8. Line runs: Point { // a compact constructor: checks the values.
  9. Line runs: if (x < 0 || y < 0) throw new IllegalArgumentException("negative").
  10. x in the Point object changes from 0 to 3. y in the Point object changes from 0 to 4.
  11. Point() has finished, so its variables are gone.
  12. b is created on the stack and points to a new Point on the heap: {x: 3, y: 4}.
  13. a.x() is a generated accessor (not getX()).
  14. x() has finished, so its variables are gone.
  15. The value it returned, 3, is stored in x.
  16. equals compares the field values: two separate objects, same data.
  17. equals() has finished, so its variables are gone.
  18. The value it returned, true, is stored in equal.
  19. Records can have extra methods: √(9 + 16) = 5.
  20. distanceFromOrigin() has finished, so its variables are gone.
  21. The value it returned, 5, is stored in d.
  22. Java calls toString(). It gets its own variables on the stack.
  23. toString() has finished, so its variables are gone.
  24. It prints Point[x=3, y=4] 3 true 5.0.
  25. Point[x=3, y=4] 3 true 5.0. A one-line declaration gave a complete, immutable data class.

Common mistakes

Best practices

Key takeaways

Check yourself

How do you read field y of a Point p?

Answer: p.y(). Accessors match the field names.

Can you change a record's field after creation?

Answer: No. Fields are final.

·

More in Modern Java (10–21)