Java Records: Data Classes
In Java 14 (as a preview feature) and officially in Java 16, the concept of records was introduced. Records are a special type of class designed to simplify the creation of immutable data classes.
In traditional Java, creating a simple data class requires boilerplate code, including:
- Fields
- Constructor
- Getters
equals()andhashCode()toString()
Records automatically generate these methods, reducing the need for manual implementation.
Get Santiago’s stories in your inbox
Join Medium for free to get updates from this writer.
Records require a single line of code to declare fields and generate all necessary boilerplate.
Immutability
Fields in a record are final and cannot be reassigned.
Auto-Generated Methods
Records provide default implementations for:
toString()equals()hashCode()
No Setters
Records are designed for immutability, so setters are not allowed.
Additional Methods
You can define additional methods, but fields cannot be re-initialized.
Code Example
Represent a simple Book object:
public record Book(String title, String author, double price) {
// Additional methods are allowed
public String getSummary() {
return title + " by " + author + " costs $" + price;
}
}public class MainBook {
public static void main(String[] args) {
Book book = new Book("Title", "Author", 10.99);
System.out.println(book.title());
System.out.println(book.author());
System.out.println(book.price());
System.out.println(book.getSummary());
System.out.println(book);
}
}Before records, defining data classes involved writing a lot of boilerplate code. For example, a typical Java POJO (Plain Old Java Object) for a Person class might look like this:
import java.util.Objects;
public class Person {
private final String name;
private final int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}This class has over 34 lines of code for a simple data object.
With records, the same Person class can be defined in one line:
public record Person(String name, int age) {}Records are a great addition to Java for handling simple, immutable data. They promote cleaner, more readable code.





