Records: short immutable data classes
32 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Many classes only carry fixed values: a point, an amount, a result row. A record declares such an immutable class in one line, and Java writes the constructor, accessors, equals(), hashCode() and toString().
One line instead of forty
A record is a special kind of class for immutable data, declared like record Student(String name, int marks) { }. From its components Java writes private final fields, a constructor, accessors, equals(), hashCode() and toString(). Records arrived in Java 16.
The immutable Rupees class in Design your own immutable class (opens in a new tab) took twenty lines for one value. A record writes those parts for you from one header line.
Example 1 · A record and what it gives you
record Student(String name, int marks) { }
public class RecordDemo { public static void main(String[] args) { Student a = new Student("Kavya", 92); Student b = new Student("Kavya", 92); System.out.println(a); System.out.println(a.name() + " scored " + a.marks()); System.out.println(a.equals(b) + " " + (a == b)); System.out.println(a.hashCode() == b.hashCode()); }}Student[name=Kavya, marks=92] Kavya scored 92 true false true
What this code does
- One line gives a constructor, accessors
name()andmarks(), and a readabletoString(). equals()compares the values, soa.equals(b)istrue;==still compares references. Equal records have equal hash codes.
The values in brackets are the record's components. The record is final, its fields are private final, and there are no setters. Accessors use the component name with no get: a.name(), not a.getName().
Checking values: the compact constructor
A compact constructor is a record constructor written without a parameter list, like Rupees { ... }. Its parameters have the component names; it checks or adjusts them, and Java assigns the fields automatically at its end.
A Rupees record must never hold a negative amount. Put the check in a compact constructor and throw IllegalArgumentException when it fails.
Example 2 · Validation in a compact constructor
record Rupees(int amount) { Rupees { if (amount < 0) { throw new IllegalArgumentException("Negative amount: " + amount); } }
Rupees plus(Rupees other) { return new Rupees(amount + other.amount); }
Rupees minus(Rupees other) { return new Rupees(amount - other.amount); }}
public class CompactDemo { public static void main(String[] args) { Rupees fee = new Rupees(1200); System.out.println(fee.plus(new Rupees(300))); try { fee.minus(new Rupees(2000)); } catch (IllegalArgumentException e) { System.out.println("Refused: " + e.getMessage()); } System.out.println(fee); }}Rupees[amount=1500] Refused: Negative amount: -800 Rupees[amount=1200]
What this code does
Rupees { ... }has no parameter list; it checksamount, and Java assigns the field after it.plusandminusreturn new records through the same constructor, so everyRupeesthat exists is valid.
Do not write this.amount = amount; there: Java assigns the fields itself, after the block. You may change a parameter first, like name = name.trim();, and the changed value is what gets stored.
Order of execution
Inside new Ticket(" Arjun ", "WL")
Tap the steps in the order they happen.
Adding your own methods
A record body can hold normal methods, static methods and static fields, and it can implement interfaces. To "change" a record, a with-method returns a new one.
Example 3 · Methods, a static factory and a with-method
record Ticket(String passenger, String seat) { Ticket { passenger = passenger.trim(); }
static Ticket waitlisted(String passenger) { return new Ticket(passenger, "WL"); }
boolean isConfirmed() { return !seat.equals("WL"); }
Ticket withSeat(String newSeat) { return new Ticket(passenger, newSeat); }}
public class TicketRecordDemo { public static void main(String[] args) { Ticket t = Ticket.waitlisted(" Arjun "); Ticket c = t.withSeat("S5-22"); System.out.println(t + " confirmed? " + t.isConfirmed()); System.out.println(c + " confirmed? " + c.isConfirmed()); }}Ticket[passenger=Arjun, seat=WL] confirmed? false Ticket[passenger=Arjun, seat=S5-22] confirmed? true
What this code does
- The compact constructor trims the name before Java stores it.
waitlistedis a static factory: a named way to create a record. withSeatreturns a newTicket;tstays waitlisted.
Example 4 · A record can implement an interface
interface Shape { double area();}
record Circle(double r) implements Shape { public double area() { return 3.14 * r * r; }}
record Rectangle(double w, double h) implements Shape { public double area() { return w * h; }}
public class ShapeRecordDemo { public static void main(String[] args) { Shape[] shapes = { new Circle(10), new Rectangle(3, 4) }; double total = 0; for (Shape s : shapes) { System.out.println(s + " area " + s.area()); total = total + s.area(); } System.out.println("Total area: " + total); }}Circle[r=10.0] area 314.0 Rectangle[w=3.0, h=4.0] area 12.0 Total area: 326.0
What this code does
- Records cannot use
extends, but they can implement interfaces, so they work with polymorphism. - The interface method is
public, so the record'sarea()must bepublictoo.
A record cannot use extends, but implementing an interface is enough for polymorphism: a Shape[] can hold circles and rectangles that are records.
What records cannot do
A record's state is exactly its components. So there are no setters, no extra instance fields and no extends, and javac stops each of them.
Example 5 · Mistake: a setter in a record
record Student(String name, int marks) { void setMarks(int marks) { this.marks = marks; }}
public class SetterDemo { public static void main(String[] args) { Student s = new Student("Rohan", 70); s.setMarks(75); System.out.println(s); }}SetterDemo.java:3: error: cannot assign a value to final variable marks
this.marks = marks;
^
1 errorWhat this code does
- Record fields are
final, so javac refuses any assignment after construction. - To get a changed record, write a method that returns
new Student(name, newMarks).
Example 6 · The array trap
record Marks(String name, int[] scores) { }
public class ArrayTrapDemo { public static void main(String[] args) { Marks a = new Marks("Diya", new int[] { 80, 90 }); Marks b = new Marks("Diya", new int[] { 80, 90 }); System.out.println(a.equals(b));
a.scores()[0] = 10; System.out.println(a.scores()[0]); }}false 10
What this code does
- The generated
equals()compares the array fields with==, so two records with the same marks are not equal. - The accessor returns the inside array, so outside code can change it. For data with arrays, a normal class with defensive copies is the better choice.
An extra field such as int bonus; in the body gives field declaration must be static. Arrays are the trap that compiles: the field is final but the array is not, and the generated equals() compares array references.
Record or class?
Use a record when the object is just its values: two objects with the same values should be equal. Use a normal class when it changes over time, needs inheritance or hides data.
record Point(int x, int y) { } // just its values: a record
class Account { // changes over time: a class private int balance;
void deposit(int amount) { balance = balance + amount; }}A record shows every component through public accessors and toString(), so it is no place for a password. Data with arrays inside is better as a class with defensive copies, as in the last lesson.
Next step
Check your understanding
12 quick questions