Java / Java 21 Coding Standards Interview Questions
What is a record in Java 21, and why do coding standards recommend it for data carriers?
A record is a special class declaration that compresses a data carrier down to its essential fields; the compiler generates the constructor, accessors, equals(), hashCode(), and toString() automatically from the declared components.
public record OrderLine(String sku, int quantity, BigDecimal unitPrice) {}
Coding standards recommend records for pure data carriers because they remove an entire class of bugs: a hand-written POJO can forget to include a field in equals(), or expose a mutable setter that breaks an invariant elsewhere in the code. A record's fields are final by default and its generated methods are always consistent with its declared components.
The standard boundary is that a record should only be used when the type is a transparent carrier of data with no independent identity or internal mutable state; an entity with a lifecycle, such as a JPA-managed row, is still better modeled as a regular class.
More Related questions...