Record
- Java course
- Intermediate
- Lesson 28/116
- 5 min
Learn immutable data classes with record.
Record
From Java 16 onwards, record is used to define immutable data carriers. A record automatically generates fields, a constructor, getters, toString, equals and hashCode methods. It greatly reduces code duplication.
Example: record Point(int x, int y) { }. This single line generates x and y fields, a constructor, x() and y() accessors, toString, equals and hashCode. An instance is created with new Point(3, 4); x is read with p.x(). Records are immutable; fields cannot be changed after creation. This is advantageous for data safety.
Record accessor
In records, reading a field's value does not use a get prefix; the field name is called directly with parentheses. For x the accessor is p.x(), for y it is p.y(). This differs from classic getters.
Example: After defining record Point(int x, int y) { }, you write Point p = new Point(3, 4);. p.x() returns three, p.y() returns four. If you write getX() you get a compile error; because the record accessor is x(). This difference gives records a cleaner syntax. toString also comes automatically; System.out.println(p) prints Point[x=3, y=4].
Practice Define the Point record
Define a record named Point with int x and int y components. In a main method create an instance with new Point(3, 4). Call the x() and y() accessors and print the values on separate lines.
Starter code
// Define the Point record
// Add x and y components
// Instantiate and print in mainSample solution
record Point(int x, int y) { }
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p.x());
System.out.println(p.y());
}
}Expected output
3 4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can record fields be changed after creation?
- Only from the same package
- No, they are immutable Correct answer
- Yes, always
- Only from subclasses
Explanation: Record fields are immutable; they cannot be changed.
2 Match the record parts
| Term | Meaning |
|---|---|
record |
Keyword |
Point |
Record name |
int x, int y |
Components |
p.x() |
Accessor |
3 Complete the record accessor call
record Point(int x, int y) { }
Point p = new Point(3, 4);
int val = p.____;
record Point(int x, int y) { }
Point p = new Point(3, 4);
int val = p.x();
Explanation: The record accessor is the field name with parentheses.