Reading history

Immutable Objects in Java: Final Fields, Defensive Copies and Records

6 min read 0 views

Learn to write truly immutable Java classes: why final is not enough, defensive copies, with-methods, records with compact constructors and safe map keys.

An immutable object can never change after it is created. String, Integer, LocalDate and records all work this way. Immutable objects are easier to reason about, safe to share between threads and safe to use as map keys. But making a class truly immutable takes more than adding final: a single mutable list inside can leak changes. This lesson shows the traps and the rules that avoid them.

In this lesson you will learn

  • Why final fields alone do not make an object immutable
  • Defensive copies in and out
  • “Changing” an immutable object by returning a new one
  • Records and compact constructors
  • Why mutable map keys get lost

You should know static and final, records and equals and hashCode.

Final Is Not Enough: Defensive Copies

import java.util.ArrayList;
import java.util.List;

public class Main {
    // Looks safe, but the list inside can still be changed from outside
    static final class LeakyCourse {
        private final String title;
        private final List<String> students;
        LeakyCourse(String title, List<String> students) { this.title = title; this.students = students; }
        List<String> students() { return students; }
    }

    // Truly immutable: final fields, copies in and out, no setters
    static final class Course {
        private final String title;
        private final List<String> students;
        Course(String title, List<String> students) {
            this.title = title;
            this.students = List.copyOf(students);     // defensive copy, also unmodifiable
        }
        List<String> students() { return students; }   // safe to share: nobody can change it
        Course withStudent(String name) {               // "change" = make a new object
            List<String> more = new ArrayList<>(students);
            more.add(name);
            return new Course(title, more);
        }
        @Override public String toString() { return title + " " + students; }
    }

    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Nusrat", "Arif"));

        LeakyCourse leaky = new LeakyCourse("Java", names);
        names.add("Intruder");                         // change the caller's list...
        leaky.students().add("Another");               // ...or the returned list
        System.out.println("Leaky course: " + leaky.students());

        names = new ArrayList<>(List.of("Nusrat", "Arif"));
        Course course = new Course("Java", names);
        names.add("Intruder");
        System.out.println("Immutable course: " + course);
        try {
            course.students().add("Another");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify the returned list");
        }
        Course bigger = course.withStudent("Tania");
        System.out.println("Original: " + course + ", new: " + bigger);
    }
}

Output

Leaky course: [Nusrat, Arif, Intruder, Another]
Immutable course: Java [Nusrat, Arif]
Cannot modify the returned list
Original: Java [Nusrat, Arif], new: Java [Nusrat, Arif, Tania]
  • LeakyCourse has only final fields and no setters, yet its student list grows from 2 to 4 names. final stops the field from pointing to a different list, but not the list itself from changing.
  • The leak happens twice: the constructor keeps the caller’s own list, and students() hands that same list back out.
  • Course fixes both with List.copyOf in the constructor. The copy is separate from the caller’s list and is itself unmodifiable, so it is safe to return directly.
  • withStudent shows how to “change” an immutable object: build and return a new object with the change, leaving the original untouched. String.replace and LocalDate.plusDays work the same way.

Records, and Why Keys Must Not Change

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    // Records are shallowly immutable: final fields, no setters
    record Point(int x, int y) {
        Point move(int dx, int dy) { return new Point(x + dx, y + dy); }
    }

    // A record can still hold a mutable list, so copy it in the constructor
    record Team(String name, List<String> members) {
        Team {
            members = List.copyOf(members);
        }
    }

    // A mutable key is dangerous in a HashMap
    static class MutableKey {
        int id;
        MutableKey(int id) { this.id = id; }
        @Override public boolean equals(Object o) { return o instanceof MutableKey k && k.id == id; }
        @Override public int hashCode() { return Integer.hashCode(id); }
    }

    public static void main(String[] args) {
        Point p = new Point(2, 3);
        Point q = p.move(1, 1);
        System.out.println(p + " stays the same; moved copy is " + q);

        Team t = new Team("Dev", new ArrayList<>(List.of("Mou", "Rubel")));
        System.out.println(t);

        Map<MutableKey, String> map = new HashMap<>();
        MutableKey key = new MutableKey(1);
        map.put(key, "first");
        key.id = 99;                                    // change the key after storing it
        System.out.println("get(new MutableKey(1))  -> " + map.get(new MutableKey(1)));
        System.out.println("get(new MutableKey(99)) -> " + map.get(new MutableKey(99)));
        System.out.println("map still has " + map.size() + " entry, but it is lost");

        String s = "java";
        String upper = s.toUpperCase();
        System.out.println(s + " / " + upper + "  (String methods return new strings)");
    }
}

Output

Point[x=2, y=3] stays the same; moved copy is Point[x=3, y=4]
Team[name=Dev, members=[Mou, Rubel]]
get(new MutableKey(1))  -> null
get(new MutableKey(99)) -> null
map still has 1 entry, but it is lost
java / JAVA  (String methods return new strings)
  • A record’s fields are final and it has no setters. move returns a new Point, so the original stays at (2, 3).
  • Records are only shallowly immutable: a record holding a mutable list could still have that list changed. The compact constructor Team { members = List.copyOf(members); } copies it before the field is set.
  • The MutableKey is stored under id 1, then changed to 99. Its hash code changed, so the map now looks for it in the wrong place. Neither id 1 nor id 99 finds it, but it still takes up space. Immutable keys make this bug impossible.
  • toUpperCase returns a new string; the original “java” is unchanged. Every String method behaves like this.

Rules for an Immutable Class

RuleWhy
Make the class final (or use a record)A subclass could add mutable state
Make every field private finalFields are set once, in the constructor
Provide no settersReturn a new object for every “change”
Copy mutable inputs in the constructorThe caller cannot change your data later
Never return mutable internals directlyReturn an unmodifiable copy or view

Common Mistakes

  1. Assuming final makes an object immutable. It only fixes the reference.
  2. Using Collections.unmodifiableList on the caller’s list without copying it first. The caller can still change the original.
  3. Storing arrays in “immutable” classes. Arrays are always mutable; copy them with clone() or use a list.
  4. Using mutable objects as HashMap keys or HashSet elements.

Practice Exercises

Exercise 1. Make a record Money(long paisa) with a method plus(Money other) that returns a new Money.

Show answer
record Money(long paisa) {
    Money plus(Money other) { return new Money(paisa + other.paisa); }
}
// new Money(1050).plus(new Money(250)) -> Money[paisa=1300]

Exercise 2. A record Scores(int[] values) leaks, because arrays are mutable. Fix it.

Show answer
record Scores(int[] values) {
    Scores { values = values.clone(); }                 // copy in
    public int[] values() { return values.clone(); }    // copy out
}

Simpler still: store a List<Integer> created with List.copyOf.

Frequently Asked Questions

Do immutable objects waste memory by creating copies?

They create more short-lived objects, but Java’s garbage collector is very good at cleaning those up. In return you avoid defensive copies elsewhere and whole classes of bugs, and you can share objects freely.

Why are immutable objects thread-safe?

Threads cause problems when one changes data while another reads it. If nothing can ever change, there is nothing to coordinate, so no locks are needed.

Summary

  • Immutable objects never change after construction.
  • final fixes references, not the objects they point to.
  • Copy mutable inputs in and never hand internals out.
  • Return new objects for changes; use records with compact constructors.

Next: BlockingQueue and ConcurrentHashMap.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *