0Pricing
Java Academy · Lesson

Introducing Records

Declare records as concise immutable data holders and understand their auto-generated members.

Introducing Records

Java Records (Java 16+) are a concise way to declare immutable data carrier classes. They auto-generate boilerplate: constructor, getters, equals, hashCode, and toString.

Declaring a Record

Use the record keyword followed by the record name and a component list. Each component becomes a private final field and a public accessor method.

record Point(double x, double y) {}

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

All lessons in this course

  1. Introducing Records
  2. Compact Constructors and Validation
  3. Custom Methods on Records
  4. Records vs Classes vs Lombok
← Back to Java Academy