A passenger books a sleeper seat on a night bus from Bengaluru to Chennai. The seat costs $50, and the passenger applies a 20% coupon. The app should charge this passenger $40 and keep quoting $50 to everyone else. If the fare is an object that any code can change, one coupon can change the price for the whole bus.
Immutability means that an object cannot change after it is built.
The principle
An immutable object gets all its values when it is built and keeps them. To "change" it, we build a new object with the new values. Java's String works this way: name.toUpperCase() gives back the upper-case text and leaves name as it was.
A class is immutable when:
- every field is
privateandfinal, and the constructor sets them all; - no method changes a field, so there are no setters;
- the class is
final, so a subclass cannot add state that changes; - no caller can change something the object holds, such as a list it was given.
The gain is that any code can hold a reference, and no other code can change what it sees. We can pass the object to any method, keep it in a map and hand it out from a getter.
The principle does not say that every object must be immutable. A booking has a passenger name record (PNR) number, and its status moves from confirmed to cancelled. It is the same booking before and after, so it stays one object that changes. An object like this, known by an identity such as its PNR, is an entity. Immutability fits values: an amount of money, a date range, a set of seats. Two values with the same contents can stand in for each other. Two bookings with the same contents cannot.
Example: a bus seat's fare
Each Trip holds one Money, the fare for any seat on that bus. The first Money has a method that changes its amount. Subtracting in place is easy and creates no new object:
public class Money { private long dollars; public Money(long dollars) { this.dollars = dollars; } public long dollars() { return dollars; } public void subtract(long amount) { this.dollars -= amount; }}Trip.seatFare() returns its Money field itself. That is fine while every caller only reads it. Then the product team asks for coupons: FIRST20 takes 20% off, and the payment page must show the seat fare, the coupon and the amount to pay. A developer writes this:
public class CouponService { public Money apply(Money fare, int percentOff) { fare.subtract(fare.dollars() * percentOff / 100); return fare; }}The payment page calls Money seatFare = trip.seatFare() and works out the $10 coupon. Then it calls Money toPay = coupons.apply(seatFare, 20). apply does not make a new amount. It subtracts $10 from the object it was given and returns that same object. So seatFare, toPay and the trip's own field are three names for one object, and all three now say $40.
One line causes two bugs. The payment page shows a seat fare of $40, a coupon of $10 and a total of $40, which do not add up. The next passenger on the same bus is quoted $40, and after a second coupon, the third passenger is quoted $32.
We could make Trip.seatFare() return a copy. But every class that holds a Money would have to remember to copy it, and one forgotten copy brings the bug back. It is simpler to make Money impossible to change.
A fare that cannot change
A Java record is the short way to write an immutable class. Its fields are private final, it has no setters, no class can extend it, and it gets equals, hashCode and toString from its fields.
public record Money(long dollars) { public Money { if (dollars < 0) { throw new IllegalArgumentException("negative amount: " + dollars); } } public Money minus(Money other) { return new Money(dollars - other.dollars); } public Money percent(int percent) { return new Money(dollars * percent / 100); }}minus and percent return a new Money and leave the old one alone. The constructor refuses a negative amount. Nothing can change a Money after that check, so every Money stays valid. The coupon becomes:
public class CouponService { public Money apply(Money fare, int percentOff) { Money discount = fare.percent(percentOff); return fare.minus(discount); }}CouponService cannot repeat the old bug even by mistake, because Money has no method that changes it. Its field is final, so Java guarantees that every thread that gets a Money sees the amount it was built with. Many booking threads can read one Money without a lock.
When final is not enough
A final field always points at the same object, but that object can still change. A seat hold for two seats shows this:
import java.util.List; public record SeatHold(String tripId, List<String> seats, Money total) {}The seat picker builds a hold from its own list, and the passenger then taps one more seat:
List<String> picked = new ArrayList<>(List.of("L4", "L5"));SeatHold hold = new SeatHold("BLR-MAA-2210", picked, new Money(100));picked.add("L6");The record's seats field is final, but it points at the seat picker's own ArrayList. When the passenger taps L6, the hold lists three seats with a total for two. The fix is to copy the list in the record's constructor:
import java.util.List; public record SeatHold(String tripId, List<String> seats, Money total) { public SeatHold { seats = List.copyOf(seats); }}List.copyOf returns a list that cannot be changed, and it refuses a null seat. Now picked.add does not reach the hold, and hold.seats().add("L7") throws UnsupportedOperationException. The total needs no copy, because a Money cannot change.
When not to
Some objects exist to change. A Booking keeps its PNR and its SeatHold in final fields, but its status lives in a field that cancel() changes. Building a new booking for every status change would leave two objects for one booking, and other code could keep the old one. A large object that changes often, such as a seat map updated on every tap, would also be copied whole on each change. One mutable object owned by one class is simpler there.
In an interview
When you draw a class, say whether it is a value or an entity. Make values records, and say why: they can be shared, used as map keys and read by many threads without a lock. The Splitwise design keeps every amount in a Money record. The Flyweight page shares one style object across many cells, and that is safe only because the style cannot change.
Common mistakes:
- Making everything immutable. A booking's status changes, and a new booking object for each change makes the design harder, not safer.
- Trusting
finalon a collection. Afinallist field can still be changed through the list. Copy it withList.copyOf. - A method that changes
thisand returns it. The firstapplylooked like it returned a new amount, but it returned the same object, changed.
Summary
- An immutable object gets its values when it is built and never changes. A "change" builds a new object.
- In Java this takes
private finalfields, no setters, afinalclass, and a copy of any collection it is given. A record gives the first three. - Entities like a booking stay mutable, and the values they hold stay immutable.