The Plain Picture#
A printed receipt: a fixed set of facts that never changes after printing. You don't need to design a receipt from scratch each time — the format is standard.
The Real Name#
A record (Java 16+) is a class for immutable data, written in one line. The compiler generates the private final fields, the
constructor, the accessor methods, and correct equals, hashCode and toString.
record QuizResult(String student, int points) {
QuizResult {
// "compact constructor": validation only
if (points < 0) throw new IllegalArgumentException("points < 0");
}
QuizResult withBonus(int extra) {
return new QuizResult(student, points + extra);
} // "changes" return new records
}QuizResult r1 = new QuizResult("Priya", 180);
QuizResult r2 = r1.withBonus(20);
System.out.println(
r1 + " " + r2 + " " + r1.equals(new QuizResult("Priya", 180)) + " " + r2.points()
);
// QuizResult[student=Priya, points=180] QuizResult[student=Priya, points=200] true 200Notice: toString is readable, equals compares contents (so records are safe HashMap keys — Ch 8), and the accessor is points(), not
getPoints().
Use records for: API request/response data, results, DSA helper tuples like record Cell(int r, int c) {} for visited sets.
Limits: fields are final (no setters), and records can't extend other classes (they can implement interfaces).
Check yourself
3 questionsWhat does the compiler generate for a record?
Show answerHide answer
Private final fields, a constructor, accessors, equals, hashCode, toString.
Why is record Cell(int r, int c) {} a good key for a HashSet of visited grid cells?
Show answerHide answer
It's immutable and has content-based equals/hashCode, so equal cells are found correctly.
What is a compact constructor for?
Show answerHide answer
Validating (or normalising) the arguments without repeating the field assignments.