Java Records, introduced as a preview feature in Java 14 and finalized in Java 16, offer a concise way to create immutable data classes. Records drastically reduce boilerplate code and are ideal for modeling data without behavior.
1. What Are Records in Java?
A record is a special kind of class in Java that automatically provides:
- A constructor
getters
for all fieldsequals()
, hashCode()
, and toString()
implementations
This makes records ideal for simple data carriers or value objects.
2. Basic Syntax
java
public record Person(String name, int age) {}
This is equivalent to:
java
public final class Person {
private final String name;
private final int age;
public Person(String name, int age) { ... }
public String name() { return name; }
public int age() { return age; }
public boolean equals(Object o) { ... }
public int hashCode() { ... }
public String toString() { ... }
}
3. Key Characteristics
- Immutable by default
- Final by design — you can’t extend a record
- Implements
java.lang.Record
implicitly - Fields are implicitly
private final
- Compact constructor customization is allowed
4. Customizing Constructors and Methods
You can add validation logic:
java
public record Product(String name, double price) {
public Product {
if (price < 0) throw new IllegalArgumentException("Price must be positive");
}
}
Add additional methods if needed:
java
public String displayLabel() {
return name + " - $" + price;
}
5. Records vs Traditional POJOs
FeaturePOJORecordSyntaxVerboseConciseMutabilityMutable by defaultImmutableInheritanceCan be extendedCannot be extendedBoilerplateHighMinimalIdeal Use CaseFull-featured objectsSimple data carriers
6. Use Cases for Records
- DTOs (Data Transfer Objects)
- API responses and requests
- Configuration objects
- Keys in maps (due to built-in
equals()
and hashCode()
)
7. Limitations of Records
- Cannot extend other classes
- Cannot define mutable fields
- Not suitable for entities with changing state
- Less flexible for complex business logic
8. Records and Serialization
Records are serializable, and frameworks like Jackson and Gson support them with proper configuration. Make sure to use default constructors or annotations depending on the library.
Java Records are a modern, elegant feature for clean data modeling. They encourage immutability, reduce boilerplate, and promote a more functional programming style in Java.