Skip to lesson

Records: short immutable data classes

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.

record Student(String name, int marks) { } is one line. From its header Java writes: private final fields name and marks, a constructor Student(String, int), the accessors name() and marks(), and equals(), hashCode() and toString() built from both components.

Example 1 · A record and what it gives you

RecordDemo.javaJava
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());    }}
Output
Student[name=Kavya, marks=92]
Kavya scored 92
true false
true

What this code does

  • One line gives a constructor, accessors name() and marks(), and a readable toString().
  • equals() compares the values, so a.equals(b) is true; == 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

CompactDemo.javaJava
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);    }}
Output
Rupees[amount=1500]
Refused: Negative amount: -800
Rupees[amount=1200]

What this code does

  • Rupees { ... } has no parameter list; it checks amount, and Java assigns the field after it.
  • plus and minus return new records through the same constructor, so every Rupees that 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.

record Ticket(String passenger, String seat) {
Ticket {
passenger = passenger.trim();
}
}
Ticket t = new Ticket(" Arjun ", "WL");

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

TicketRecordDemo.javaJava
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());    }}
Output
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. waitlisted is a static factory: a named way to create a record.
  • withSeat returns a new Ticket; t stays waitlisted.

Example 4 · A record can implement an interface

ShapeRecordDemo.javaJava
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);    }}
Output
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's area() must be public too.

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

SetterDemo.javaJava
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);    }}
Sample compiler output
SetterDemo.java:3: error: cannot assign a value to final variable marks
        this.marks = marks;
            ^
1 error

What 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

ArrayTrapDemo.javaJava
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]);    }}
Output
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.

Java
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