Sub topic 7
Your First Record: Data Without Boilerplate
Programs often need small objects that only hold data, like a point on a map or a name and an age. In older Java, writing one of these took many lines of repetitive code. A record is a special kind of class that holds a fixed group of values. You write one line, and Java writes the rest for you.
The Old Way: A Plain Class
This is a simple class that holds an x and a y value:
import java.util.Objects;
final class OldPoint {
private final int x;
private final int y;
OldPoint(int x, int y) {
this.x = x;
this.y = y;
}
int x() { return x; }
int y() { return y; }
@Override
public boolean equals(Object o) {
if (!(o instanceof OldPoint other)) return false;
return x == other.x && y == other.y;
}
@Override
public int hashCode() { return Objects.hash(x, y); }
@Override
public String toString() { return "OldPoint[x=" + x + ", y=" + y + "]"; }
}That is about 25 lines just to store two numbers. Code that you have to repeat in almost every class like this is called boilerplate. It takes time to write, and it is easy to get wrong.
The New Way: A Record
This record does the same job in one line:
record Point(int x, int y) {}The part in parentheses lists the components. A component is one piece of data the record holds. Here there are two components, x and y.
What Java Generates for You
From that one line, the compiler creates these members:
| Generated member | What it does | Example |
|---|---|---|
| Private final fields | Store each component | `x`, `y` |
| Canonical constructor | Takes every component, in order | `new Point(1, 2)` |
| Accessor methods | Return each component | `p.x()`, `p.y()` |
| `equals` | Compares the values of all components | `p.equals(q)` |
| `hashCode` | Gives equal records the same hash code | `p.hashCode()` |
| `toString` | Prints the name and the values | `Point[x=1, y=2]` |
A canonical constructor is the constructor that takes one argument for each component. An accessor is a method that returns a value. In a record, each accessor has the same name as its component. You call p.x(), not p.getX().
A Worked Example
Save this as Main.java and run it with java Main.java (JDK 17 or later):
import java.util.HashSet;
import java.util.Set;
record Point(int x, int y) {}
public class Main {
public static void main(String[] args) {
Point p = new Point(1, 2);
Point q = new Point(1, 2);
System.out.println(p.x()); // 1
System.out.println(p); // Point[x=1, y=2]
System.out.println(p.equals(q)); // true
System.out.println(p == q); // false
Set<Point> points = new HashSet<>();
points.add(p);
points.add(q);
System.out.println(points.size()); // 1
}
}The two points are separate objects, so p == q is false. They hold the same values, though, so equals returns true. Records use value-based equality, which means two records are equal when all their components are equal. Because hashCode follows the same rule, the HashSet treats p and q as one item.
Records Cannot Be Changed
Each field in a record is final. A final field is set once, when the object is created, and cannot be changed after that. A record has no setter methods, so to "move" a point, you create a new one:
Point moved = new Point(p.x() + 5, p.y());Data that cannot change is easier to reason about. No other part of your program can change a record after you have handed it over.
Exercise
Write a record named Book with a String title and an int pages. Create new Book("Dune", 412) and print it. What is printed, and how do you get the page count?
Show answer
Declare record Book(String title, int pages) {}. Printing it shows Book[title=Dune, pages=412]. Call the accessor book.pages() to get 412.
Exercise
Given Point a = new Point(3, 4) and Point b = new Point(3, 4), what do a.equals(b) and a == b return, and why?
Show answer
a.equals(b) returns true because records compare the values of their components. a == b returns false because a and b are two different objects in memory.