Records — immutable data carriers with auto-generated constructor, getters, equals(), hashCode(), and toString(). They eliminate boilerplate for simple data classes.
1public record Point(int x, int y) {2 // Compact constructor for validation (no parameter assignment)3 public Point {4 if (x < 0 || y < 0) throw new IllegalArgumentException("Coordinates must be non-negative");5 }67 // Custom methods8 public double distanceTo(Point other) {9 return Math.sqrt(Math.pow(x - other.x, 2) + Math.pow(y - other.y, 2));10 }1112 // Static factory method13 public static Point origin() {14 return new Point(0, 0);15 }16}1718// Auto-generates:19// - Canonical constructor: Point(int x, int y)20// - Accessor methods: x(), y() (not getX()!)21// - equals(), hashCode(), toString()2223var p = new Point(3, 4);24System.out.println(p.x()); // 325System.out.println(p.toString()); // Point[x=3, y=4]26System.out.println(p.equals(new Point(3, 4))); // true
Auto-Generated Members:
x(), y() (not getX(), getY()).Point[x=3, y=4].Restrictions:
java.lang.Record).1// Records implementing interfaces2public interface Shape {3 double area();4}56public record Circle(double radius) implements Shape {7 @Override8 public double area() {9 return Math.PI * radius * radius;10 }11}1213// Records with collections14public record Team(String name, List<String> members) {15 // Defensive copy in compact constructor16 public Team {17 members = List.copyOf(members); // Immutable copy18 }19}
When to Use:
Common Pitfalls: