Records in Java (Standard Since Java 16)
A record is a special kind of class for carrying immutable data. You declare its components once, and the compiler generates the fields, constructor, accessors, equals, hashCode and toString. Records were previewed in Java 14 and 15 and became standard in Java 16 (JEP 395), so they are available in the Java 17 LTS release.
This tutorial covers what a record generates, how to validate data, and what records cannot do.
1. Why Were Records Added?
Simple data classes, such as DTOs, query results and map keys, needed dozens of lines of boilerplate. That code is easy to get wrong, for example an equals that forgets a field. A record states the intent "this class is just its data" and removes the boilerplate completely.
2. What a Record Generates
record Book(String isbn, String title, int priceInRupees) { }
// The compiler generates:
// private final String isbn; private final String title; private final int priceInRupees;
// a canonical constructor Book(String, String, int)
// accessors isbn(), title(), priceInRupees()
// equals(), hashCode() and toString() based on all components
- A record is implicitly
finaland extendsjava.lang.Record. - Fields are
private final; there are no setters. - You may add methods, static fields and nested types, and implement interfaces.
3. Practical Examples
Example 1: Generated members and a compact constructor
import java.util.HashSet;
import java.util.Set;
public class RecordEssentials {
// Components: isbn, title, priceInRupees
record Book(String isbn, String title, int priceInRupees) {
// Compact canonical constructor: validation without repeating fields
Book {
if (isbn == null || isbn.isBlank()) {
throw new IllegalArgumentException("isbn required");
}
if (priceInRupees < 0) {
throw new IllegalArgumentException("price must not be negative");
}
title = title.strip();
}
// Extra methods are allowed
Book withDiscount(int percent) {
return new Book(isbn, title, priceInRupees * (100 - percent) / 100);
}
}
public static void main(String[] args) {
Book b1 = new Book("978-1", " Clean Code ", 650);
Book b2 = new Book("978-1", "Clean Code", 650);
System.out.println(b1); // generated toString
System.out.println("title() = " + b1.title()); // accessor, not getTitle()
System.out.println("equals = " + b1.equals(b2)); // value-based equality
System.out.println("discount = " + b1.withDiscount(20));
Set<Book> shelf = new HashSet<>(Set.of(b1));
System.out.println("contains b2? " + shelf.contains(b2)); // hashCode matches equals
try {
new Book(" ", "Untitled", 100);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Book[isbn=978-1, title=Clean Code, priceInRupees=650] title() = Clean Code equals = true discount = Book[isbn=978-1, title=Clean Code, priceInRupees=520] contains b2? true Rejected: isbn required
The compact constructor has no parameter list. It runs before the fields are assigned, so it can validate and normalise values, as with title.strip().
Example 2: Records in a real workflow
Records work well as parsed values, as interface implementations, and as results of stream collectors.
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
public class RecordsInPractice {
interface Priced {
int price();
}
// A record can implement interfaces and declare static members
record Item(String name, String category, int price) implements Priced {
static Item of(String csv) {
String[] p = csv.split(",");
return new Item(p[0], p[1], Integer.parseInt(p[2]));
}
}
// A record used as a composite map key
record CategoryStats(long count, int total) { }
public static void main(String[] args) {
List<Item> items = List.of("pen,stationery,20", "mouse,electronics,700",
"notebook,stationery,60", "cable,electronics,250").stream().map(Item::of).toList();
Map<String, CategoryStats> stats = items.stream().collect(Collectors.groupingBy(
Item::category, TreeMap::new,
Collectors.collectingAndThen(Collectors.toList(),
l -> new CategoryStats(l.size(), l.stream().mapToInt(Item::price).sum()))));
stats.forEach((k, v) -> System.out.println(k + " -> " + v));
Item cheapest = items.stream().min(Comparator.comparingInt(Item::price)).orElseThrow();
System.out.println("Cheapest: " + cheapest.name());
}
}
electronics -> CategoryStats[count=2, total=950] stationery -> CategoryStats[count=2, total=80] Cheapest: pen
4. From Declaration to Class
5. Important Points and Best Practices
- Records cannot extend another class and cannot declare instance fields outside the header.
- They are shallowly immutable: a record holding a mutable
Listcan still see that list change; copy it withList.copyOfin the constructor. - Accessor names have no
getprefix, which matters for some older frameworks. - Use records for data carriers, not for entities with identity or changing state, such as JPA entities.
6. Summary
- Records were finalised in Java 16 (JEP 395) and are part of Java 17 LTS.
- They generate fields, constructor, accessors,
equals,hashCodeandtoString. - Compact constructors validate and normalise data.
- Records are final, shallowly immutable and cannot extend classes.
Related Tutorials
7. References
Frequently Asked Questions (FAQ)
Q1. Which Java version introduced records?
Records were previewed in Java 14 and 15 and became a standard feature in Java 16 (JEP 395). Java 17 is the first LTS release that includes them.
Q2. Can a record have methods?
Yes. Records can have instance methods, static methods, static fields, nested types and can implement interfaces.
Q3. Are records immutable?
Their fields are final, so references cannot change, but referenced objects such as lists can still be mutable. Make defensive copies for full immutability.
Q4. Can a record extend another class?
No. Every record implicitly extends java.lang.Record, and Java has single inheritance.