What is a Record in Java?
A record is a special kind of class introduced in Java 16 (preview earlier), and fully standard from Java 16 onwards, designed to model immutable data. Think of it as a concise way to define a class whose main purpose is to store data.
A record automatically provides:
- Final fields
- Constructor
- Getters (called accessors)
equals()
,hashCode()
, andtoString()
methods
Syntax Example (Java 21)
// Define a record
public record Person(String name, int age) {}
// Use the record
public class Main {
public static void main(String[] args) {
Person p = new Person("Alice", 30);
// Access fields
System.out.println(p.name()); // Alice
System.out.println(p.age()); // 30
// toString() is automatically generated
System.out.println(p); // Person[name=Alice, age=30]
}
}
Here:
Person
is a record with two fields:name
andage
.p.name()
andp.age()
are automatically generated accessors.- You don’t write constructors or
equals
/hashCode
unless you want custom behavior.
Customizing Records
You can add methods or a custom constructor:
public record Person(String name, int age) {
// Custom constructor (compact form)
public Person {
if (age < 0) throw new IllegalArgumentException("Age must be non-negative");
}
// Custom method
public String greet() {
return "Hello, " + name + "!";
}
}
Usage:
Person p = new Person("Bob", 25);
System.out.println(p.greet()); // Hello, Bob!
Key Points About Records
- Records are implicitly
final
— you cannot extend a record. - Fields are private and final by default.
- Records are perfect for DTOs, value objects, and immutable data containers.
- You can implement interfaces but cannot extend another class.