Java / Java 21 Coding Standards Interview Questions
Why is a record preferred over a traditional POJO for immutable data carriers?
A hand-written immutable POJO needs a constructor, private final fields, getters, and correct equals()/hashCode()/toString() implementations - five separate places where a forgotten field or a mismatched implementation can introduce a bug, for example an equals() that checks three fields while a fourth was added later and never wired in.
public record Point(int x, int y) {} // equals, hashCode, toString, constructor, accessors all generated and kept in sync
A record collapses all of that into a single declaration where the components are the single source of truth: every generated method is derived from the same component list, so they can never drift out of sync with each other the way independently hand-written methods can.
The trade-off is that a record cannot extend another class (though it can implement interfaces) and its fields cannot be individually made mutable, so it is reserved for types that are genuinely transparent carriers of data rather than entities with identity or internal state machines.
More Related questions...