1. The DTO-class problem: why do we need record classes?
Let’s be honest: how many times have you written a class like this?
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "Point{" + "x=" + x + ", y=" + y + '}';
}
}
It’s not particularly hard, but count the lines! Now imagine you have 10 such classes, each with 5–6 fields. Even your IDE gets tired of generating this boilerplate. And if you decide to add a new field, you’ll have to adjust the constructor, getter, equals, hashCode, toString... Boring, repetitive, and error-prone.
Such classes are called DTOs (Data Transfer Objects) or Value Objects. They just hold data — that’s it. But because of the boilerplate, they’re a pain to maintain.
If it doesn’t feel like a problem yet, just wait until you have to modify 50 of these classes at once. You’ll remember record classes with special fondness!
2. Introduction to records: syntax and the magic of Java 16+
With Java 16, everything changed. A new kind of class appeared — the record. It’s designed specifically for cases where you simply need to store a set of data. The syntax is almost like a tuple in other languages.
How do you declare a record?
public record Point(int x, int y) { }
And... that’s it! You’ve just created an immutable class with two fields, a constructor, accessors, equals, hashCode, and toString. No extra boilerplate.
What does Java do “under the hood”?
- Fields x and y become private final.
- Accessors are generated automatically: int x() and int y().
- Constructor: public Point(int x, int y).
- equals/hashCode: compare all fields by value.
- toString: returns a string like "Point[x=1, y=2]".
You could say records are “DTOs on steroids”: less code, more guarantees, fewer bugs.
Immutability
All fields of a record class are automatically final. Once an object is created, you can’t change it — and the compiler enforces that.
If you try to add a setter or make a field not final, the compiler will stop you. That kind of care for your peace of mind is rare!
3. Example of using a record class
Regular class (lots of code):
public class Client {
private final String name;
private final int id;
public Client(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() { return name; }
public int getId() { return id; }
// equals, hashCode, toString ...
}
Record class (one line!):
public record Client(String name, int id) { }
Usage:
public class Main {
public static void main(String[] args) {
Client client = new Client("Ivan", 123);
System.out.println(client.name()); // Ivan
System.out.println(client.id()); // 123
System.out.println(client); // Client[name=Ivan, id=123]
}
}
Note:
- Accessor methods have the same names as the fields: name(), id().
- There is no setName() or setId() — the object cannot be modified after creation.
4. Benefits of record classes: less code, fewer bugs
Less code — more happiness
Why write 40 lines when one will do? Record classes save time and nerves, especially in large projects with many DTOs and value objects.
Immutability “by contract”
- Record classes are always final and immutable.
- The object can’t be forged or accidentally modified.
- No “weird” bugs due to state changes in unexpected places.
- Safe to use in multithreaded programs (if all fields are also immutable).
Automatic generation of equals/hashCode/toString
No need to hand-write comparison, hash computation, and pretty-print methods. It’s all done automatically and correctly.
Client c1 = new Client("Anna", 42);
Client c2 = new Client("Anna", 42);
System.out.println(c1.equals(c2)); // true
System.out.println(c1.hashCode() == c2.hashCode()); // true
System.out.println(c1); // Client[name=Anna, id=42]
Perfect for collections and keys
Record objects can be used as keys in a HashMap, elements of a HashSet, and so on — everything will work correctly, because equals and hashCode take all fields into account.
import java.util.HashMap;
import java.util.Map;
Map<Client, String> clients = new HashMap<>();
clients.put(new Client("Anna", 42), "VIP");
System.out.println(clients.get(new Client("Anna", 42))); // VIP
Explicit data description
The syntax of a record class immediately shows what data it holds and that the object is immutable. This makes the code clearer for other developers (and for you in six months).
5. Table: comparing a regular class and a record class
| Regular class | Record class | |
|---|---|---|
| Syntax | Lots of code | One line |
| Immutability | Must be implemented explicitly | Guaranteed by the compiler |
| Auto-generated methods | No | Yes (equals, hashCode, toString) |
| Adding fields | Yes | Only record components |
| Inheritance | Can be extended | Always final; cannot be extended |
| Use in collections | Must implement methods correctly | Works out of the box |
6. Evolving the learning app: example with a record class
Suppose your learning bank application needs to store account transactions: date, amount, and operation type (for example, “deposit” or “withdrawal”).
Before Java 16:
public class Transaction {
private final LocalDate date;
private final double amount;
private final String type;
public Transaction(LocalDate date, double amount, String type) {
this.date = date;
this.amount = amount;
this.type = type;
}
public LocalDate getDate() { return date; }
public double getAmount() { return amount; }
public String getType() { return type; }
// equals, hashCode, toString ...
}
With Java 16 and records:
import java.time.LocalDate;
public record Transaction(LocalDate date, double amount, String type) { }
Usage:
Transaction t = new Transaction(LocalDate.now(), 100.0, "deposit");
System.out.println(t); // Transaction[date=2024-06-01, amount=100.0, type=deposit]
System.out.println(t.amount()); // 100.0
7. Visualisation: what a record generates
Let’s look at a “desugared” record class (approximately what the compiler generates):
public final class Point extends java.lang.Record {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() { return x; }
public int y() { return y; }
@Override
public boolean equals(Object o) { /* field-by-field comparison */ }
@Override
public int hashCode() { /* hash computed from fields */ }
@Override
public String toString() { /* nice string representation */ }
}
In short: when to use a record
- When you need an immutable object with a set of data.
- When you want “honest” equals/hashCode/toString without hand-written boilerplate.
- When you build DTOs, Value Objects, pairs, triples, colors, points, ranges, keys for collections, and so on.
8. Common mistakes when working with record classes
Error #1: trying to add a setter or modify a field after creation.
A record class does not allow its fields to be modified. If you try to add a method like setX(int x), the compiler will immediately say “not allowed.” The same applies if you try to change a field directly.
Error #2: trying to add a non-static field.
In a record class, you can declare only components (the fields listed in parentheses after the record name) and static fields. Regular non-static fields are not allowed — the compiler won’t let you do it.
Error #3: using a record for mutable logic.
Record classes are not intended for objects with mutable state. If you need to change something after creation, use a regular class.
Error #4: forgetting that a record is always final.
A record class cannot be extended and cannot serve as a superclass. Attempting to break this rule will lead to a compilation error. The key idea — don’t try to “extend” a record: it’s designed as a complete immutable type.
Error #5: ignoring the auto-generated methods.
If you override equals, hashCode, or toString, be careful — don’t break their contracts, or collections and comparisons will misbehave.
GO TO FULL VERSION