A lot of Java code is simple data carriers: a class with a few fields, a constructor, getters, equals, hashCode and toString. Writing all that by hand is long and error-prone. Records, standard since Java 16, generate it for you.
One line instead of fifty
public record CourseDto(Long id, String title, int durationMonths) { }
Java automatically creates:
- private final fields for each component,
- a constructor taking all of them,
- accessor methods named after the fields:
dto.title()(notgetTitle()), - correct
equals(),hashCode()andtoString().
Records are immutable
Fields cannot be changed after creation. To “change” a value, create a new record. Immutability makes records safe to share between threads and safe as HashMap keys.
Adding validation
Use a compact constructor to check values:
public record CourseDto(Long id, String title, int durationMonths) {
public CourseDto {
if (durationMonths <= 0) throw new IllegalArgumentException("Duration must be positive");
}
}
You can also add your own methods and static factory methods.
Where records fit
- DTOs in Spring Boot: request and response bodies for REST APIs. Jackson reads and writes records as JSON.
- Return values that group several results.
- Keys in maps and sets.
Where they do not fit
JPA entities usually need a no-argument constructor and changeable fields, so keep entities as normal classes and use records for the data you send to and from the API.
Interview angle
Explain how a record differs from a normal class, why it is immutable, and how it compares with Lombok’s @Data.
Related: the four pillars of OOP in Java, how a Java HashMap works and Java Optional explained.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
