A record
is a special kind of class primarily designed to model immutable data and is often used for representing data transfer objects (DTOs), data structures, or simple containers of data.
public record Person(String name, int age) {
// No need for explicit constructor, getters, equals(), hashCode(), and toString()
}
The record
keyword automatically generates several methods for you, including:
name()
and age()
in this case).equals()
, hashCode()
, and toString()
methods based on the components.Records are inherently immutable
, meaning that their state cannot be modified once they are created. This immutability is enforced by the generated code, and attempts to modify the state of a record will result in compilation errors.