Java Records: A Whole Data Class in One Line
record Order(String id, String customer, double total) replaces a 30-line class: toString, accessors like customer(), equals and hashCode come free. A Shipment changes by copying, an Invoice compact constructor rejects -50 and tidies " inv-2031 ", and an Account stays a class.
What you will learn
- Declare a record and use its accessors, equals, hashCode and toString
- Describe what the compiler generates for a record
- Change a record by building a new copy instead of using setters
- Validate and tidy input in a compact constructor, and choose a record or a class
Before you start
- Java final and immutable objects
- Java equals and hashCode
Think of a record as a shipping label. The details are printed once, and after that nobody changes them. A record holds a fixed set of values, and Java writes the boilerplate for you.
A whole class in one line
The project's PlainOrder is the class you'd write by hand to hold three values: fields, a constructor, getters, equals, hashCode and toString, about 30 lines. Only the fields say anything new. A record says just that part:
package org.studyeasy.s05l01;
public class Ex01_OrderRecord {
// Fields, constructor, accessors, equals, hashCode, toString
record Order(String id, String customer, double total) {}
public static void main(String[] args) {
Order order = new Order("A-1001", "Priya", 749.50);
System.out.println(order); // toString for free
// Accessors are named after the fields: no "get"
System.out.println(order.customer() + " pays " + order.total());
Order same = new Order("A-1001", "Priya", 749.50);
System.out.println(order.equals(same)); // same values
System.out.println(order.hashCode() == same.hashCode());
System.out.println(order == same); // two objects
}
}
Order[id=A-1001, customer=Priya, total=749.5]
Priya pays 749.5
true
true
false
Printing shows every component by name, though we never wrote toString. There are no getters; the accessors are named after the components, so it's customer(), not getCustomer(). equals compares the values, so two orders with the same values are equal and have equal hash codes. == is still false: they're two objects. And order.total = 0; doesn't compile, because the field is final.
javap shows inside the compiled record.Open the compiled record with the javap tool and you see it: a final class that extends Record (so it can't have another parent), one private final field per component, a constructor taking them in header order, the three methods, and the accessors.
No setters: a change is a copy
record Shipment(String trackingId, String city, String status) {
Shipment withStatus(String newStatus) { // no setters: copy
return new Shipment(trackingId, city, newStatus);
}
}
Shipment placed = new Shipment("TRK-42", "Pune", "PLACED");
Shipment shipped = placed.withStatus("SHIPPED");
System.out.println(placed); // the original is untouched
System.out.println(shipped);
// Built-in equals + hashCode: a Set spots the repeat
Set<Shipment> seen = new HashSet<>();
seen.add(shipped);
seen.add(new Shipment("TRK-42", "Pune", "SHIPPED"));
System.out.println("In the set: " + seen.size());
Shipment[trackingId=TRK-42, city=Pune, status=PLACED]
Shipment[trackingId=TRK-42, city=Pune, status=SHIPPED]
In the set: 1
A record can't be changed, so withStatus (our own method) builds a second Shipment, copying the tracking id and city and putting in the new status. placed is untouched. The built-in equals and hashCode let a HashSet spot the second, equal shipment, so the set holds one.
Compact constructor: guard the data
record Invoice(String number, String customer, double amount) {
Invoice { // compact: no (...)
if (amount <= 0)
throw new IllegalArgumentException("amount must be > 0");
number = number.trim().toUpperCase(); // tidy the input
} // fields are assigned here
}
Invoice inv = new Invoice(" inv-2031 ", "Mei Lin", 1899.0);
System.out.println(inv); // number already tidied
System.out.println(inv.number().equals("INV-2031"));
try {
new Invoice("INV-2032", "Tom Walker", -50);
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
Invoice[number=INV-2031, customer=Mei Lin, amount=1899.0]
true
Rejected: amount must be > 0
Invoice { ... } with no brackets is a compact constructor. It runs in three stages: check, tidy, then assign. 1899 passes the check, the number loses its spaces and becomes capitals, and the fields are assigned at the closing brace, so the tidied number is what's stored. -50 stops at the check: the throw means no record is built. Writing this.amount = amount; inside it doesn't compile; Java does the assigning.
Facts are records, change is a class
record Txn(String type, double amount) {} // a fact: fixed
static class Account { // it changes: a class
double balance;
final List<Txn> history = new ArrayList<>();
void deposit(double amount) {
balance += amount; // state moves
history.add(new Txn("DEPOSIT", amount)); // facts pile up
}
}
Balance: 750.0
Txn[type=DEPOSIT, amount=500.0]
Txn[type=DEPOSIT, amount=250.0]
Depositing 500 and then 250 moves the balance to 750, and each deposit adds a Txn to the history. The balance changed; the transactions were never edited. Ask one question: will this value change? No means a record (Order, Invoice, Txn), yes means a class. Turn Account into a record and balance += a fails: cannot assign a value to final variable balance.
Recap
| Feature | Example |
|---|---|
| Declare | record Order(String id, String customer, double total) {} |
| Accessors | order.customer(), no "get" |
| Free methods | toString, equals, hashCode by value |
| Change | build a copy: withStatus("SHIPPED") |
| Validate | compact constructor: Invoice { ... } |
Records pair well with sealed classes and record patterns, coming next.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Classes and Objects: One Blueprint, Many Cars
Six loose variables for two cars doesn't scale. A Car class is the blueprint; new builds each car with its own brand, speed and fuel. Plus field defaults, and why two variables can point at one car.
Java Constructors and the this Keyword
A constructor decides how an object is born: new Car("Toyota", 42.5) arrives filled in. this.brand vs brand, a second constructor that calls this(brand, 50.0), and why new Car() stops compiling once you write your own.
Java Instance Methods, Getters, Setters and toString
Give a Car class behaviour: accelerate() changes only this car's speed, private fields are reached through getSpeed and setSpeed, and toString turns Car@1b6d3586 into 'Toyota doing 60 km/h'.
Java static: Fields, Methods and Blocks Shared by the Whole Class
A static field lives once on the class: every Car ticks the same carsBuilt counter while keeping its own brand. Static methods need no object, a static block runs before main, and main is static so the JVM can start with no object.
