Sub topic 7
Your First Record: Data Without Boilerplate
Many classes in a program do one simple job: they hold a few pieces of data together. A point has an x and a y. A person has a name and an age. An order has an ID and a total.
Java has a special kind of class for this job. It is called a record. A record is a class whose main purpose is to carry a fixed group of values. You list the values once, and Java writes the rest of the code for you.
This chapter shows what a record is, why it saves you work, and what Java creates for you automatically.
The Problem: Boilerplate
Boilerplate is code you have to write again and again, even though it is almost the same every time. Plain data classes are full of it.
Here is a regular class that holds a point with two numbers. It is written the careful way, so it behaves correctly when you compare points or print them.
import java.util.Objects;
public class PointClass {
private final int x;
private final int y;
public PointClass(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 instanceof PointClass)) return false;
PointClass other = (PointClass) o;
return x == other.x && y == other.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
@Override
public String toString() {
return "PointClass[x=" + x + ", y=" + y + "]";
}
public static void main(String[] args) {
PointClass p = new PointClass(1, 2);
System.out.println(p);
}
}That is about 40 lines just to say "a point has an x and a y." Each part has a job:
- The fields store the values.
- The constructor sets the fields when you create a point.
- The getters let other code read the values.
equalsdecides when two points count as the same.hashCodegives a number that collections such asHashSetuse to find objects fast.toStringturns the point into readable text.
If you add a third value, such as z, you must update six places. If you forget one, you get a bug that is hard to spot.
The Solution: One Line
Here is the same idea as a record:
record Point(int x, int y) {}That one line gives you everything the long class had. Let's use it.
Save this as Main.java:
public class Main {
public static void main(String[] args) {
Point p = new Point(1, 2);
System.out.println(p.x()); // 1
System.out.println(p.y()); // 2
System.out.println(p); // Point[x=1, y=2]
System.out.println(p.equals(new Point(1, 2))); // true
}
}
record Point(int x, int y) {}Compile and run it:
javac Main.java
java MainThe output is:
1
2
Point[x=1, y=2]
trueReading a Record Declaration
Let's look at the parts of record Point(int x, int y) {}.
| Part | Meaning |
|---|---|
| `record` | The keyword that says "this is a record, not a regular class." |
| `Point` | The name of the record. It follows the same naming rules as a class. |
| `(int x, int y)` | The **record header**. It lists the **components**, which are the values the record holds. |
| `{}` | The **body**. It is empty here. Later chapters put methods inside it. |
A component is one named value in the record header. Point has two components: x and y. Each component has a type and a name, just like a method parameter.
What Java Generates for You
From the header alone, the Java compiler creates these members:
| Generated member | What it looks like for `Point` | What it does |
|---|---|---|
| Private final fields | `private final int x;` and `private final int y;` | Store the values. `final` means they cannot be changed after creation. |
| Canonical constructor | `Point(int x, int y)` | Takes one argument per component, in header order, and sets the fields. |
| Accessor methods | `int x()` and `int y()` | Return each value. |
| `equals` | `p.equals(q)` | True when both are `Point`s and every component is equal. |
| `hashCode` | `p.hashCode()` | Built from all components, so equal points get equal hash codes. |
| `toString` | `Point[x=1, y=2]` | Shows the record name and each component. |
The canonical constructor is the constructor whose parameters match the record header exactly. "Canonical" here means "the standard one." The next chapter shows how to add checks to it.
Accessors Have No "get"
An accessor is a method that returns a component's value. In a record, the accessor has exactly the same name as the component. You call p.x(), not p.getX().
Equality: Same Values Means Equal
A record compares by its values. Two Point objects with the same x and y are equal, even if they are different objects in memory.
This is different from the == operator. For objects, == asks "are these the exact same object?" The equals method asks "do these hold the same data?"
public class EqualityDemo {
public static void main(String[] args) {
Point a = new Point(3, 4);
Point b = new Point(3, 4);
Point c = a;
System.out.println(a == b); // false: two separate objects
System.out.println(a.equals(b)); // true: same component values
System.out.println(a == c); // true: c refers to the same object as a
System.out.println(a.hashCode() == b.hashCode()); // true
}
}
record Point(int x, int y) {}Use equals when you want to compare records by their data. That is almost always what you want.
Why hashCode Matters
Collections like HashSet and HashMap use hashCode and equals together to find items. A regular class that forgets to write them will not work properly as a set item or a map key. Records always get both, so they work in these collections from the start.
import java.util.HashSet;
import java.util.Set;
public class SetDemo {
public static void main(String[] args) {
Set<Cell> visited = new HashSet<>();
visited.add(new Cell(1, 2));
visited.add(new Cell(1, 2)); // equal to the first, so not added again
visited.add(new Cell(3, 4));
System.out.println(visited.size()); // 2
System.out.println(visited.contains(new Cell(3, 4))); // true
}
}
record Cell(int row, int col) {}The set has only two cells, because the two Cell(1, 2) objects are equal.
Records with Different Component Types
Components can be any type: numbers, strings, other records, lists, and so on.
public class PersonDemo {
public static void main(String[] args) {
Person ada = new Person("Ada", 36);
System.out.println(ada.name()); // Ada
System.out.println(ada.age()); // 36
System.out.println(ada); // Person[name=Ada, age=36]
Line line = new Line(new Point(0, 0), new Point(5, 5));
System.out.println(line); // Line[start=Point[x=0, y=0], end=Point[x=5, y=5]]
System.out.println(line.end().x()); // 5
}
}
record Person(String name, int age) {}
record Point(int x, int y) {}
record Line(Point start, Point end) {}Notice how toString nests nicely. Line prints its two Point components using their own toString.
Edge Cases Worth Knowing
A Record with No Components
A record can have an empty header. All such objects are equal to each other.
public class EmptyDemo {
public static void main(String[] args) {
System.out.println(new Nothing()); // Nothing[]
System.out.println(new Nothing().equals(new Nothing())); // true
}
}
record Nothing() {}This is rarely useful by itself, but it is legal.
Null Components Are Allowed
By default, a record accepts null for any component that is an object type. The generated equals, hashCode, and toString handle null safely.
public class NullDemo {
public static void main(String[] args) {
Person unknown = new Person(null, 0);
System.out.println(unknown); // Person[name=null, age=0]
System.out.println(unknown.equals(new Person(null, 0))); // true
}
}
record Person(String name, int age) {}If you want to reject null, you add a check in a constructor. The next chapter shows how.
Fields Cannot Be Reassigned
The fields are final, so no code can replace a component's value after the record is created. To "change" a point, you create a new one:
Point moved = new Point(p.x() + 1, p.y());A later chapter explains one catch: if a component is a mutable object like a List, the list itself can still change.
Records Can Be Generic
A record can take type parameters, just like a class:
public class PairDemo {
public static void main(String[] args) {
Pair<String, Integer> score = new Pair<>("Ada", 95);
System.out.println(score.first() + " scored " + score.second()); // Ada scored 95
}
}
record Pair<A, B>(A first, B second) {}Summary
- A record is a class for holding a fixed group of values.
- You declare the components once in the header.
- Java generates private final fields, a canonical constructor, accessors,
equals,hashCode, andtoString. - Accessors use the component name with no
getprefix. - Records compare by value, so they work well in sets and as map keys.
Exercise
Write a record named Book with components title (a String) and pages (an int). What does System.out.println(new Book("Dune", 412)) print, and how do you read the page count?
Show answer
Declare it as record Book(String title, int pages) {}. Printing it shows Book[title=Dune, pages=412]. You read the page count with book.pages(), not getPages().
Exercise
Given record Point(int x, int y) {}, what do these print? Point a = new Point(2, 2); Point b = new Point(2, 2); System.out.println(a == b); System.out.println(a.equals(b));
Show answer
The first line prints false, because a and b are two separate objects. The second prints true, because the generated equals compares the x and y values, and they match.
Exercise
You add three Cell objects to a HashSet: new Cell(0, 0), new Cell(0, 1), and new Cell(0, 0), where Cell is record Cell(int row, int col) {}. What is the size of the set, and why?
Show answer
The size is 2. The record's generated equals and hashCode treat the two Cell(0, 0) objects as equal, so the set keeps only one of them.