Skip to lesson

Immutable Classes and Records

Interviewers ask for the steps to write an immutable class, then look for the defensive-copy mistake, then ask how records make it shorter and where they still leak. A "final fields and no setters" answer loses marks.

Steps to write an immutable class

An immutable class is one whose objects cannot change after the constructor finishes. String, Integer and LocalDate are immutable.

The recipe has five steps and interviewers expect all five. The code builds a small student class where a "change" returns a new object.

Example 1 · A complete immutable class

ImmutableStudent.javaJava
final class Student {    private final String name;    private final int marks;
    Student(String name, int marks) {        if (marks < 0 || marks > 100) {            throw new IllegalArgumentException("Marks must be 0-100");        }        this.name = name;        this.marks = marks;    }
    String getName() {        return name;    }
    int getMarks() {        return marks;    }
    Student withMarks(int newMarks) {             // a "change" returns a new object        return new Student(name, newMarks);    }
    @Override    public String toString() {        return name + " (" + marks + ")";    }}
public class ImmutableStudent {    public static void main(String[] args) {        Student before = new Student("Asha", 78);        Student after = before.withMarks(85);        System.out.println("before: " + before);        System.out.println("after:  " + after);        System.out.println("same object? " + (before == after));    }}
Output
before: Asha (78)
after:  Asha (85)
same object? false

What this code does

  • All five steps are visible: final class, private final fields set once, no setters, validation in the constructor, and withMarks returning a new object.
  • before still shows 78 after the "update": anyone holding it can rely on it never changing.

Must know:

  • declare the class final (or use a private constructor with factories)
  • make every field private final and set it in the constructor
  • provide no setters; "changes" return a new object (withMarks(95))
  • make defensive copies of mutable fields on the way in and on the way out

Order of execution

The immutable recipe

Put the five steps in the order you would say them.

The defensive copy trap with a List or Date field

A defensive copy is a fresh copy of a mutable object, made when it enters or leaves your class, so outside code cannot change your internal state.

final freezes only the reference, not the list or date inside. The code shows a leaky class and a safe one side by side.

Example 2 · Leaky vs safe: the defensive copy

DefensiveCopy.javaJava
import java.util.ArrayList;import java.util.List;
final class LeakyReport {    private final List<Integer> marks;
    LeakyReport(List<Integer> marks) {        this.marks = marks;    }
    List<Integer> getMarks() {        return marks;    }}
final class SafeReport {    private final List<Integer> marks;
    SafeReport(List<Integer> marks) {        this.marks = List.copyOf(marks);    }
    List<Integer> getMarks() {        return marks;                             // safe: cannot be changed    }}
public class DefensiveCopy {    public static void main(String[] args) {        List<Integer> input = new ArrayList<>(List.of(70, 85));
        LeakyReport leaky = new LeakyReport(input);        SafeReport safe = new SafeReport(input);
        input.add(10);                            // caller changes its list later        leaky.getMarks().add(0);                  // caller changes through the getter        System.out.println("leaky: " + leaky.getMarks());        System.out.println("safe:  " + safe.getMarks());
        try {            safe.getMarks().add(0);        } catch (UnsupportedOperationException e) {            System.out.println("safe report cannot be changed");        }    }}
Output
leaky: [70, 85, 10, 0]
safe:  [70, 85]
safe report cannot be changed

What this code does

  • LeakyReport has final fields and no setters, yet its marks changed twice: through the caller's original list and through the returned list.
  • SafeReport copies on the way in with List.copyOf, so neither path reaches its data, and the returned list throws on add.

If the constructor stores the caller's List directly, the caller can still call add on it and your "immutable" object changes. If a getter returns the internal list, any caller can change it the same way.

Copy in the constructor (List.copyOf(marks)) and return the unmodifiable copy, or another copy, from the getter. java.util.Date has the same problem because setTime mutates it; copy it, or use the immutable LocalDate instead.

Find the bug

Where does it leak?

Tap the line that breaks immutability.

The constructor receives a list from the caller.

Round 1 of 3

Records as concise immutable data carriers

A record is a concise class for immutable data, declared as record Student(String name, int marks) {}. Java generates the fields, constructor, accessors, equals, hashCode and toString.

A record writes most of the immutable recipe for you. The code shows what it generates, a validating constructor, and equal records in a set.

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 3 · What a record gives you

RecordDemo.javaJava
import java.util.HashSet;import java.util.Set;
record Marks(String subject, int value) {    Marks {                                       // compact constructor: validate        if (value < 0 || value > 100) {            throw new IllegalArgumentException("Invalid marks: " + value);        }        subject = subject.trim().toUpperCase();   // normalise before fields are set    }
    boolean passed() {                            // extra methods are allowed        return value >= 40;    }}
public class RecordDemo {    public static void main(String[] args) {        Marks m = new Marks(" maths ", 72);        System.out.println(m);        System.out.println(m.subject() + " " + m.value() + " passed=" + m.passed());
        Set<Marks> set = new HashSet<>();        set.add(new Marks("Maths", 72));        set.add(new Marks("MATHS", 72));        System.out.println("equal records in a set: " + set.size());
        try {            new Marks("Physics", 120);        } catch (IllegalArgumentException e) {            System.out.println(e.getMessage());        }    }}
Output
Marks[subject=MATHS, value=72]
MATHS 72 passed=true
equal records in a set: 1
Invalid marks: 120

What this code does

  • One line declares the fields, constructor, accessors (subject(), value()), toString, equals and hashCode. The compact constructor validates and normalises the subject.
  • Because the subject is upper-cased before the field is set, "Maths" and "MATHS" give equal records, so the set holds one.

The accessors are named after the components (name(), marks()), and the record is implicitly final. A compact constructor, Student { ... } with no parameter list, validates or normalises the arguments before the fields are set.

Records can add methods and implement interfaces, but cannot extend a class or add instance fields.

Benefits asked: thread safety, safe map keys, caching

Interviewers ask for the benefits in three words: thread safety, safe map keys, caching. The code shows an immutable object used as a key and read by two threads.

Two students share one Fee object. Mutable Fee: rohan.fee.amount is changed in place, so priya.fee and rohan.fee both see 40000. Immutable Fee: rohan.fee = rohan.fee.discount(5000) makes a new Fee of 40000 for Rohan only, and Priya still points to the unchanged Fee of 45000.

Example 4 · Immutable keys and sharing across threads

ImmutableBenefits.javaJava
import java.util.HashMap;import java.util.List;import java.util.Map;
record SeatKey(String train, int seat) { }
public class ImmutableBenefits {    static final List<String> HOLIDAYS = List.of("26 Jan", "15 Aug", "2 Oct");   // shared, cannot change
    public static void main(String[] args) throws InterruptedException {        Map<SeatKey, String> booking = new HashMap<>();        booking.put(new SeatKey("12627", 33), "Asha");        System.out.println("lookup: " + booking.get(new SeatKey("12627", 33)));
        int[] counts = new int[2];        Thread t1 = new Thread(() -> counts[0] = HOLIDAYS.size());        Thread t2 = new Thread(() -> counts[1] = HOLIDAYS.size());        t1.start();        t2.start();        t1.join();        t2.join();        System.out.println("both threads read " + counts[0] + " and " + counts[1] + " holidays, no locks needed");    }}
Output
lookup: Asha
both threads read 3 and 3 holidays, no locks needed

What this code does

  • A record key never changes, so a fresh SeatKey("12627", 33) always finds the booking: no lost-key bug is possible.
  • Two threads read the same immutable list without any synchronized, because nobody can write to it. The join calls make the output order fixed.

Immutable objects are thread-safe without locks: nobody writes, so there are no races. They are safe map keys: their hash codes never change, so the lost-key bug cannot happen. They are easy to cache and share: one instance can be handed to every caller, as Integer.valueOf and the string pool do.

The cost is a new object for every change. For values that change often, build with a mutable helper (such as StringBuilder) and produce an immutable result at the end.

Trap: a record with a mutable list component

Shallow immutability means the fields cannot be reassigned, but the objects they point to can still change. A record that holds a List is only shallowly immutable.

A record with a list component looks immutable but is not. The code shows the leak and the one-line fix.

Example 5 · Trap: a record with a mutable list, and the fix

RecordListTrap.javaJava
import java.util.ArrayList;import java.util.List;
record LeakyTeam(String name, List<String> members) { }
record Team(String name, List<String> members) {    Team {        members = List.copyOf(members);           // defensive copy in the compact constructor    }}
public class RecordListTrap {    public static void main(String[] args) {        List<String> people = new ArrayList<>(List.of("Asha", "Ravi"));
        LeakyTeam leaky = new LeakyTeam("Coding Club", people);        Team safe = new Team("Coding Club", people);
        people.add("Meera");        leaky.members().add("Neel");        System.out.println("leaky: " + leaky.members());        System.out.println("safe:  " + safe.members());
        try {            safe.members().add("Neel");        } catch (UnsupportedOperationException e) {            System.out.println("Team members cannot be changed from outside");        }    }}
Output
leaky: [Asha, Ravi, Meera, Neel]
safe:  [Asha, Ravi]
Team members cannot be changed from outside

What this code does

  • LeakyTeam is a record, but its list is the caller's mutable ArrayList, so both the original list and the accessor change its contents.
  • Team copies the list in its compact constructor; later changes to people do not reach it, and its accessor returns an unmodifiable list.

record Team(String name, List<String> members) {} stores whatever list you pass, so the caller can add members later, and team.members().add(...) works too. The record's equals and hashCode then change, so a team used as a map key can get lost.

The fix is one line in a compact constructor: members = List.copyOf(members);. Now the record holds its own unmodifiable copy, and the accessor returns a list that throws on add.

Predict the output

Does the record change?

Predict the exact output, then read the reason.

Round 1 of 3

A record stores the list it was given.

import java.util.ArrayList;
import java.util.List;
record Team(String name, List<String> members) { }
public class Round1 {
public static void main(String[] args) {
List<String> list = new ArrayList<>(List.of("Asha", "Ravi"));
Team t = new Team("Blue", list);
list.add("Neel");
System.out.println(t.members().size());
}
}

Next step

Check your understanding

12 quick questions