LOW-LEVEL DESIGN · DESIGN PRINCIPLES · TECHNIQUE · 16 OF 48

Immutability and Value Objects in Java: Records and Copies

Objects that never change after they are built remove a whole family of bugs. Covers final fields, Java records, validation in the constructor, defensive copies of lists, "with" methods that return a new object, equality by value instead of identity, and why immutable objects are safe to share between threads.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 14

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 155 lines, with a small main() demo. Save it as ImmutabilityDemo.java, then run javac ImmutabilityDemo.java && java ImmutabilityDemo.

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * Immutability and value objects in a shop cart and a hotel booking.
 * Money is in minor units (paise), never a double.
 */
public class ImmutabilityDemo {

    // ---------- Before: a shared mutable price ----------

    static final class MutablePrice {
        private long amount;

        MutablePrice(long amount) {
            this.amount = amount;
        }

        long amount() {
            return amount;
        }

        void setAmount(long amount) {
            this.amount = amount;
        }
    }

    record OldCartLine(String item, MutablePrice price) { }

    // ---------- After: immutable value objects ----------

    record Money(long minor, String currency) {
        Money {
            if (minor < 0) {
                throw new IllegalArgumentException("negative amount");
            }
            Objects.requireNonNull(currency);
        }

        Money plus(Money other) {
            if (!currency.equals(other.currency)) {
                throw new IllegalArgumentException("currency mismatch");
            }
            return new Money(minor + other.minor, currency);
        }

        Money percentOff(int percent) {
            return new Money(minor * (100 - percent) / 100, currency);
        }
    }

    record CartLine(String item, Money price) { }

    record StayDates(LocalDate in, LocalDate out) {
        StayDates {
            Objects.requireNonNull(in);
            Objects.requireNonNull(out);
            if (!out.isAfter(in)) {
                throw new IllegalArgumentException("check-out must be after check-in");
            }
        }

        StayDates withOut(LocalDate newOut) {
            return new StayDates(in, newOut);   // validated again by the constructor
        }

        long nights() {
            return out.toEpochDay() - in.toEpochDay();
        }
    }

    /** A hand-written immutable class with a defensive copy. */
    static final class HotelBooking {
        private final String id;
        private final StayDates dates;
        private final Money perNight;
        private final List<String> guests;

        HotelBooking(String id, StayDates dates, Money perNight, List<String> guests) {
            this.id = Objects.requireNonNull(id);
            this.dates = Objects.requireNonNull(dates);
            this.perNight = Objects.requireNonNull(perNight);
            this.guests = List.copyOf(guests);   // copy in: the caller's list cannot reach us
        }

        List<String> guests() {
            return guests;                       // already unmodifiable, safe to return
        }

        HotelBooking withDates(StayDates newDates) {
            return new HotelBooking(id, newDates, perNight, guests);
        }

        Money total() {
            return new Money(perNight.minor() * dates.nights(), perNight.currency());
        }

        @Override
        public String toString() {
            return id + " " + dates.nights() + " nights, guests " + guests + ", total " + total();
        }
    }

    public static void main(String[] args) {
        System.out.println("-- before: aliasing bug --");
        MutablePrice shared = new MutablePrice(20000);
        OldCartLine tea = new OldCartLine("tea", shared);
        OldCartLine chai = new OldCartLine("chai", shared);
        tea.price().setAmount(18000);            // meant for tea only
        System.out.println("chai now costs " + chai.price().amount() + " (wrong)");

        System.out.println("-- after: immutable Money --");
        Money price = new Money(20000, "INR");
        CartLine tea2 = new CartLine("tea", price);
        CartLine chai2 = new CartLine("chai", price);
        tea2 = new CartLine(tea2.item(), tea2.price().percentOff(10));
        System.out.println(tea2 + " | " + chai2);

        System.out.println("-- equality by value --");
        Money a = new Money(20000, "INR");
        Money b = new Money(20000, "INR");
        System.out.println("same object: " + (a == b) + ", equals: " + a.equals(b)
                + ", in set: " + Set.of(a).contains(b));
        System.out.println("sum: " + a.plus(b));

        System.out.println("-- defensive copy --");
        List<String> names = new ArrayList<>(List.of("Meera"));
        List<String> view = Collections.unmodifiableList(names);
        StayDates stay = new StayDates(LocalDate.of(2026, 3, 10), LocalDate.of(2026, 3, 12));
        HotelBooking booking = new HotelBooking("B-77", stay, new Money(350000, "INR"), names);
        names.add("Ravi");                        // caller changes its own list later
        System.out.println("view sees " + view.size() + " names, booking keeps " + booking.guests());

        System.out.println("-- change means a new object --");
        HotelBooking longer = booking.withDates(stay.withOut(LocalDate.of(2026, 3, 13)));
        System.out.println("old: " + booking);
        System.out.println("new: " + longer);
        try {
            stay.withOut(LocalDate.of(2026, 3, 9));
        } catch (IllegalArgumentException e) {
            System.out.println("rejected: " + e.getMessage());
        }

        System.out.println("-- shared safely across threads --");
        Money fee = new Money(500, "INR");
        Money total = List.of(a, b, price).parallelStream()
                .map(m -> m.plus(fee))
                .reduce(new Money(0, "INR"), Money::plus);
        System.out.println("parallel total: " + total);
    }
}

Notes

The problem

Here is the bug. A cart has two lines, tea and chai, and both were built with the same price object for two hundred rupees. Later a promotion takes ten percent off tea, by calling set amount on tea's price. But that is the very same object chai holds. Chai's price silently changes to one hundred and eighty as well. Nothing looks wrong at the call site. This is aliasing, two references to one mutable object.

Shared mutable price
MutablePrice p = new MutablePrice(200);
CartLine tea = new CartLine("tea", p);
CartLine chai = new CartLine("chai", p);

// ten percent off tea only
tea.price().setAmount(180);

chai.price().amount();  // 180 too!

The idea

An immutable object gets all its state in the constructor and never changes after that. The rules are simple. Make every field private and final. Add no setters. Stop subclasses from adding mutable state, by making the class final. Check the values in the constructor. Copy any mutable input, like a list, and never hand out your internal list. To change something, return a brand new object instead.

Immutable class rules
  • • all fields private final
  • • no setters
  • • class cannot be extended
  • (final, or a record)
  • • validate in the constructor
  • • copy mutable inputs in,
  • never hand internals out
  • • "change" = return a NEW
  • object

Value objects

A value object is an object defined only by its values, like a number. Two Money objects of two hundred rupees are equal, and you can swap one for the other without anyone noticing. Dates, addresses and amounts are value objects, and they should be immutable. An entity is different. Booking B seventy seven keeps its identity even when its dates change. Entities can change, but they are built out of immutable values.

Value object vs entity
  • value object: no identity
  • two 200 INR notes are
  • equal; swap them freely
  • Money, StayDates, Address
  • entity: has an identity
  • that stays while data
  • changes
  • Booking #B-77, a Guest

Records

Java records are made for this. Declaring record Money with an amount and a currency gives you private final fields, accessor methods, and equals, hash code and to string based on the values. The compact constructor is where you validate, for example no negative amounts. Arithmetic like plus never changes this object. It checks the currencies match and returns a new Money. Amounts are stored in paise, as a long, so there is no floating point error.

A record as a value object
record Money(long minor, String currency) {
  Money {
    if (minor < 0)
      throw new IllegalArgumentException();
  }
  Money plus(Money o) {
    sameCurrency(o);
    return new Money(minor + o.minor,
                     currency);
  }
}

The fix

Back to the cart, with an immutable Money. To discount tea, we ask its price for a new Money that is ten percent lower, and give tea a new line with that price. The original two hundred rupee object is untouched, so chai still costs two hundred. Sharing one Money between many lines is now completely safe, and even saves memory. The bug from the start of the lesson cannot be written any more.

Defensive copies

A trap: final only stops you from pointing the field at another list. It does not stop someone from adding to the list itself. If HotelBooking just stored the caller's list, the caller could add a guest later and the booking would change behind its back. So copy it in the constructor with List dot copy of. That copy is also unmodifiable, so returning it from the getter is safe. Records with a list field need the same copy in their compact constructor.

Copy lists in
final class HotelBooking {
  private final List<String> guests;

  HotelBooking(List<String> guests, ...) {
    this.guests = List.copyOf(guests);
  }
  List<String> guests() {
    return guests; // already read-only
  }
}

Copy vs view

Be careful with the older helper, Collections dot unmodifiable list. It returns a read-only view over the original list. You cannot change it through the view, but if the original list changes, the view shows the change. List dot copy of makes a real snapshot instead, which is what an immutable object needs. Also remember that records are only shallowly immutable: a record holding a mutable list is not immutable unless you copy it.

Two read-only lists
List<String> src = new ArrayList<>();
var view = Collections
    .unmodifiableList(src);
var copy = List.copyOf(src);

src.add("Ravi");
view.size();  // 1: sees the change
copy.size();  // 0: a real snapshot

Changing a value

How do you change an immutable value? You do not. You build a new one. A with method returns a copy with one field different. StayDates with out returns new dates with a later checkout. Because every new object goes through the constructor, the rule that checkout must be after check-in is checked every time. A mutable class with two setters could pass through an invalid state in between. An immutable one never can.

with methods
record StayDates(LocalDate in,
                 LocalDate out) {
  StayDates {
    if (!out.isAfter(in)) throw ...;
  }
  StayDates withOut(LocalDate d) {
    return new StayDates(in, d);
  }
}

Equality by value

Value objects compare by value. Two Money objects of two hundred rupees are two different objects in memory, so comparing them with double equals is false, but equals is true, and a set holding one contains the other. Records do this for you. Immutability also matters for map keys. If a mutable key changes after it goes into a hash map, its hash code changes and the map can no longer find it. Immutable keys can never get lost.

Value equality
var a = new Money(20000, "INR");
var b = new Money(20000, "INR");

a == b       // false: two objects
a.equals(b)  // true: same value

Set.of(a).contains(b)  // true

mutable keys in a HashMap can
get lost when they change

Thread safety for free

Here is the bonus. Race conditions need two things: shared data and someone changing it. Immutable objects remove the second one. Many threads can read the same booking or the same Money at once, with no locks and no volatile. Java also guarantees that final fields set in the constructor are visible to other threads once the object is safely built. So immutable objects are thread safe for free, and easy to cache and share.

Costs and limits

There are costs. Every change creates a new object. For small values that is cheap, and the garbage collector handles short lived objects well, but rebuilding a huge structure in a tight loop can hurt. And some things really do change over time, like a booking moving from held to confirmed. Keep such entities mutable, but build them out of immutable values. Java's own String, LocalDate, Integer and BigDecimal are all immutable.

When to be careful
  • each change makes a new
  • object: fine for values,
  • costly in tight loops over
  • big structures
  • entities change over time:
  • keep them mutable but build
  • them from immutable values
  • Java has many already:
  • String, LocalDate, Integer

In interviews

In a design round, make every small data type a record and say why. Ticket, Money and Vehicle are records, built once, compared by value and safe to share across gate threads. Then point out that only a few classes hold changing state, so that is exactly where locking is needed. Common mistakes are storing money as a double, and getters that return the internal mutable list.

Say it like this
  • "Ticket, Money and Vehicle
  • are records: built once,
  • compared by value, safe to
  • share across gate threads."
  • "Only ParkingLot and Spot
  • hold changing state, so
  • that is where locking goes."
  • mistakes: money as double,
  • getters returning live lists

Interview questions

How do you make a class immutable in Java?

Make all fields private and final, provide no setters, prevent subclassing by making the class final or using a record, validate in the constructor, defensively copy mutable inputs, and never return internal mutable objects. Methods that would change state return a new instance instead.

What is a value object?

An object whose identity does not matter, only its values, such as Money, a date range or an address. Two value objects with the same values are equal and interchangeable. They should be immutable and implement equals and hashCode by value.

What is the difference between a value object and an entity?

An entity has an identity that stays the same while its attributes change, like a booking with an id. A value object has no identity of its own and is defined entirely by its values. Entities are usually built from immutable value objects.

Are Java records immutable?

Records are shallowly immutable: their fields are final and there are no setters. If a component is a mutable object such as an ArrayList, the record can still change through it, so copy such components in the compact constructor, for example with List.copyOf.

What is the difference between Collections.unmodifiableList and List.copyOf?

unmodifiableList returns a read-only view of the original list, so later changes to the original show through. List.copyOf creates an independent unmodifiable copy (or returns the same list if it is already an unmodifiable copy), which is what an immutable class needs.

Why are immutable objects thread safe?

Race conditions need shared state that is being modified. Immutable objects are never modified after construction, and Java guarantees that final fields set in the constructor are visible to other threads once the reference is published, provided this does not escape during construction.

Why should map keys be immutable?

A HashMap places a key by its hashCode. If a mutable key changes after insertion, its hash changes and lookups search the wrong bucket, so the entry is effectively lost. Immutable keys keep a stable hashCode.

What are the downsides of immutability?

Every change allocates a new object, which can cost memory and time for large structures updated often. Some domain objects naturally change over time, so they stay mutable entities built from immutable values. Builders or with methods help when objects have many fields.