Why this matters
- Data carriers are everywhere — DTOs, map keys, method return values — and writing them by hand means fifty lines where one would do, plus a real risk of an
equalsthat forgets a field. - Records are the foundation for sealed hierarchies and record patterns, so they are the entry point to modern data-oriented Java.
- Knowing exactly what a record does and does not give you is the difference between using them well and reaching for one where a class belongs.
The declaration
Loading compiler…
That single line produces everything below.
Loading compiler…
Hand-written class
private final fields
Constructor
Getters
equals + hashCode
toString
record Point(int x, int y)
One lineEverything above generated
Fields are final and the class is implicitly final, so a record is immutable by construction.
Loading compiler…
What you get, and what you give up
Guaranteed by the compiler
- All fields are
private final— the record is shallowly immutable. - The class is
final— it cannot be extended. - A canonical constructor taking every component in declaration order.
- An accessor per component, named exactly like the component with no
getprefix. equalsandhashCodecomparing every component, always consistent with each other.toStringlisting every component with its name.
What a record cannot do
- Extend another class. Every record implicitly extends
java.lang.Record. - Declare instance fields beyond its components. State lives only in the header.
- Be non-final or abstract, so no record hierarchies.
- Be mutable. There are no setters and you cannot add them meaningfully.
A record can implement interfaces, declare static fields and methods, add instance methods, define nested types, and carry annotations — so it is a real class, just a constrained one.
Loading compiler…
The rest of this guide is part of Pro
Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.
Still to come · 5 sections
- Validation with a compact constructor
- The shallow immutability trap
- When a record is the right choice
- Records and serialization frameworks
- Common misreadings
Test yourself
Answer these before moving on — recall is what makes it stick.