Lesson 7 of 10
record - Immutable Data Carriers (Java 16+)
A record is a special class for immutable data carriers. It auto-generates the constructor, private final fields, getters, equals, hashCode, and toString. Records eliminate boilerplate for pure data objects - use them whenever you need a class that just holds data.
record vs class
// 40 lines of boilerplate class:
public class Point {
private final int x;
private final int y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int x() { return x; } // records use x() not getX()
public int y() { return y; }
@Override public boolean equals(Object o) { ... }
@Override public int hashCode() { ... }
@Override public String toString() { ... }
}
// 1 line with record:
public record Point(int x, int y) {}
// Auto-generates: constructor, final fields, x(), y(), equals, hashCode, toString
// Usage
Point p1 = new Point(3, 4);
Point p2 = new Point(3, 4);
System.out.println(p1); // Point[x=3, y=4]
System.out.println(p1.equals(p2)); // true
System.out.println(p1.x()); // 3 (no getX() - just x())
// Add validation in compact constructor
public record BookDTO(String isbn, String title, double price) {
// Compact constructor (no parameter list - uses the record's)
public BookDTO {
if (isbn == null || isbn.isBlank()) throw new IllegalArgumentException("ISBN required");
if (price < 0) throw new IllegalArgumentException("Price negative");
title = title.trim(); // can normalise fields in compact constructor
}
}
// Records can have:
// - Additional methods
// - Static fields and methods
// - Implement interfaces
// Records CANNOT:
// - Extend other classes (implicitly extends Record)
// - Have additional instance fields
// - Have mutable fields (all fields are final)Quick Quiz
Tip
Tip
Practice record Immutable Data Carriers Java 16 in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for record - Immutable Data Carriers (Java 16+)
Practice Task
Note
Practice Task - (1) Write a working example of record Immutable Data Carriers Java 16 from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with record Immutable Data Carriers Java 16 is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?