Immutable Classes and Records
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}before: Asha (78) after: Asha (85) same object? false
What this code does
- All five steps are visible:
finalclass,private finalfields set once, no setters, validation in the constructor, andwithMarksreturning a new object. beforestill 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 finaland 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
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"); } }}leaky: [70, 85, 10, 0] safe: [70, 85] safe report cannot be changed
What this code does
LeakyReporthasfinalfields and no setters, yet its marks changed twice: through the caller's original list and through the returned list.SafeReportcopies on the way in withList.copyOf, so neither path reaches its data, and the returned list throws onadd.
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 3Records 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.
Example 3 · What a record gives you
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()); } }}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,equalsandhashCode. 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.
Example 4 · Immutable keys and sharing across threads
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"); }}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. Thejoincalls 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
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"); } }}leaky: [Asha, Ravi, Meera, Neel] safe: [Asha, Ravi] Team members cannot be changed from outside
What this code does
LeakyTeamis a record, but its list is the caller's mutableArrayList, so both the original list and the accessor change its contents.Teamcopies the list in its compact constructor; later changes topeopledo 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.
Next step
Check your understanding
12 quick questions