Records and compact constructors
What you will learn
A record is a compact class declaration for data represented by a fixed list of named components. The compiler supplies component accessors and, unless explicitly declared, value-oriented equality, hashing and text representation. Use a compact constructor to validate or normalize inputs before the record is initialized.
- Construct and read a record and predict its generated equality.
- Enforce a component invariant in a compact constructor and expose behavior through an interface.
Use a fresh folder for each complete Main.java example. Compile with javac --release 21 Main.java and run java Main. Requires JDK 21 or a compatible newer JDK. The examples use the standard library only.
Represent a shelf location
public class Main { record Shelf(String aisle, int number) {} public static void main(String[] args) { Shelf a = new Shelf("B", 3); Shelf b = new Shelf("B", 3); System.out.println(a.aisle() + a.number()); System.out.println(a.equals(b)); System.out.println(a == b); System.out.println(a.hashCode() == b.hashCode()); }}Expected output:
B3truefalsetrueThe record header declares the data shape. The constructor accepts components in that order; accessors are aisle() and number(), not getAisle(). Equal component values make these records equal even though the two objects are distinct. Equal values must have equal hashes; the reverse is not guaranteed.
Rules and mental model
Records became a permanent language feature in Java 16. A record is implicitly final, extends java.lang.Record, and can implement interfaces. Its component fields are private and final. It may declare static fields and ordinary methods, but not additional instance fields. An explicit canonical constructor repeats component names and types and assigns fields; the compact form omits the parameter list and lets the compiler assign fields. An alternate constructor delegates to another constructor. Generated toString is helpful for debugging, not a stable serialization format. A record is designed around its components; do not override accessors or equality in a way that breaks the expected copy/equality relationship.
Validate and normalize a product code
public class Main { record Product(String code, int units) { Product { if (code == null || code.isBlank()) { throw new IllegalArgumentException("Code required"); } if (units < 0) throw new IllegalArgumentException("Negative units"); code = code.strip(); } } public static void main(String[] args) { Product item = new Product(" A12 ", 0); System.out.println(item.code() + ":" + item.units()); try { new Product("B", -1); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } }}Expected output:
A12:0Negative unitsThe compact constructor has implicit parameters matching the header. Reassigning code normalizes the parameter; the compiler initializes the component fields after the body succeeds. Zero units are allowed. A rejected input does not produce a successfully constructed record.
Combine a record with an interface and an alternate constructor
public class Main { interface Costed { int cost(); } record Ticket(int seats, int unitCost) implements Costed { Ticket { if (seats < 1 || seats > 100 || unitCost < 0 || unitCost > 1000) { throw new IllegalArgumentException("Invalid ticket"); } } Ticket(int seats) { this(seats, 12); } public int cost() { return seats * unitCost; } } public static void main(String[] args) { Costed ticket = new Ticket(3); System.out.println(ticket.cost()); System.out.println(new Ticket(3).equals(new Ticket(3, 12))); }}Expected output:
36trueThe shorter constructor delegates to the canonical constructor, keeping validation in one place. The interface lets callers use the behavior without needing the specific record type. The bounds also keep multiplication within int range.
Common mistakes
Writing this.units = units inside a compact constructor is a compile-time error. Change the parameter if normalization is required, or use a full canonical constructor for explicit field assignment. A record does not automatically reject null components, and final fields do not make referenced objects immutable. Use a regular class for evolving identity and controlled state changes; persistence and serialization framework support must be verified separately.
Practice
Create record RoomBooking(String room, int hours). Trim the room name, reject null/blank names and hours outside 1–8, and provide a one-argument constructor that defaults to one hour. Print the normalized room and hours, equality with an explicitly constructed equivalent record, and the message for a rejected nine-hour booking.
Check your result with the chapter practice task and explain why it works.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Records and compact constructors — knowledge check
Apply enum, record and ownership rules using Java 21-compatible examples.
Given record Point(int x, int y) {}, how do you read x?
What is true for two distinct Shelf records with aisle B and number 3?
How should a compact constructor normalize a String component called code?
How can Ticket(int seats) reuse validation in Ticket(int seats, int unitCost)?
Which declaration can a record implement?