Java
Record
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].
Exercise 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.
Show example 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());
}
}
Test yourself
-
Can record fields be changed after creation?
- Only from the same package
- No, they are immutable
- Yes, always
- Only from subclasses
Show answer
No, they are immutable — Record fields are immutable; they cannot be changed.
-
Match the record parts
- record
- Keyword
- Point
- Record name
- int x, int y
- Components
- p.x()
- Accessor
-
Complete the record accessor call
record Point(int x, int y) { }
Point p = new Point(3, 4);
int val = p.____;
Show answer
record Point(int x, int y) { }
Point p = new Point(3, 4);
int val = p.x();
Next lesson: Summary - Encapsulation