Immutable objects

An immutable object cannot change after its constructor returns. Its fields are final, it has no setter, every operation returns a new object, and a caller can share it without a copy. The class String is the model, and this lesson builds two more.

final fields

A final field is assigned once, in the declaration or in the constructor. The compiler checks every other assignment, so the object cannot be given another value after it exists. final on the class and on the methods is a different rule, and lesson 054 takes it.

A final field of a mutable type is a constant reference, not a constant value: a final list can still be added to. Immutability is a property of the object and of everything it points at, which is why the array below is copied in both directions.

A value with no setters

The money class stores the amount in cents and offers one operation that returns a new amount. The original is untouched, and the caller decides whether to keep the result.

The file Money.java:

public final class Money { private final int cents; Money(int cents) { this.cents = cents; } Money plus(Money other) { return new Money(cents + other.cents); } int cents() { return cents; } @Override public String toString() { return String.format("%d.%02d", cents / 100, cents % 100); } public static void main(String[] args) { Money a = new Money(1050); Money b = new Money(250); Money sum = a.plus(b); System.out.println(a + " + " + b + " = " + sum); System.out.println("a unchanged: " + a); System.out.println("same object: " + (a == sum)); } }

javac -Xlint:all Money.java
java Money

10.50 + 2.50 = 13.00
a unchanged: 10.50
same object: false

plus reads the field of the other object, adds it to its own and builds a third. The class is final so that nobody can add a mutable subclass, and every field is final so that no method can change one.

A defensive copy

An array field breaks immutability unless both ends copy it: the constructor copies the argument so the caller cannot change the field, and the getter copies the field so the caller cannot change it from outside. Both copies are the same idea.

import java.util.Arrays; public class Range { private final int[] values; Range(int[] values) { this.values = values.clone(); } int[] values() { return values.clone(); } public static void main(String[] args) { int[] source = {1, 2, 3}; Range range = new Range(source); source[0] = 99; int[] copy = range.values(); copy[1] = 99; System.out.println(Arrays.toString(range.values())); } }

javac -Xlint:all Range.java
java Range

[1, 2, 3]

The two writes to 99 reached the source array and to a copy, and the range still holds 1, 2 and 3. This is exactly the pair of clones of lesson 038, with the addition that the class is final and every field is final, so no other path to the array exists.

String as the model

A String is final, its characters are final, and every method returns a new string. That is why a string can be a map key, a constant shared by a thousand callers, and a field of an immutable class without a copy. The same rules produce the same properties in the classes of this lesson.

The cost of immutability is a new object for every change, which a loop that builds text pays for, as lesson 025 showed. The benefit is that no caller can invalidate the object, so it can be shared, cached and read from many threads without a lock.

Exercises

  1. Add a times(int factor) method to Money and check that the original is unchanged.
  2. Remove one final from Money.java and try to write a setter.
  3. Return the array from Range.values() without cloning and observe the change.
  4. Make a list field in an immutable class and return List.copyOf from the getter.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What keeps an immutable object from changing?

    Answer

    Final fields, no setters and new objects for every operation

    The fields cannot be reassigned, nothing writes them, and operations return new values.

  2. Why does the constructor of Range clone its argument?

    Answer

    The caller cannot change the field through the passed array

    Keeping the caller reference would let the caller write into the object state.

  3. What is a final field of a list type?

    Answer

    A constant reference whose list can still change

    final stops a new assignment to the field, not calls that change the list object.

  4. What does this program print? public class Q1 { public static void main(String[] args) { M a = new M(10); M b = a.plus(5); System.out.println(a.value + " " + b.value); } } class M { final int value; M(int value) { this.value = value; } M plus(int amount) { return new M(value + amount); } }

    Answer

    10 15

    plus returns a new object and leaves the original at 10.

  5. What does this program print? import java.util.Arrays; public class Q2 { public static void main(String[] args) { int[] a = {1, 2}; Range r = new Range(a); a[0] = 9; System.out.println(Arrays.toString(r.values())); } } class Range { private final int[] values; Range(int[] values) { this.values = values.clone(); } int[] values() { return values.clone(); } }

    Answer

    [1, 2]

    The constructor copied the array, so the later write to a is not visible in the range.

  6. What does this program print? public class Q3 { public static void main(String[] args) { String a = "x"; String b = a.toUpperCase(); System.out.println(a + b); } }

    Answer

    xX

    toUpperCase returns a new string and a keeps its lower-case value.

  7. What is the cost of an immutable class?

    Answer

    Every change allocates a new object

    The original cannot change, so a change is a new value, which costs an allocation.

  8. What does this program print? import java.util.Arrays; public class Q4 { public static void main(String[] args) { int[] a = {1, 2}; int[] b = a.clone(); b[0] = 9; System.out.println(Arrays.toString(a)); } }

    Answer

    [1, 2]

    clone creates a new array, and the write to the clone leaves the original alone.

  9. Why is String safe as a key of a map?

    Answer

    It cannot change after it is created

    A key that cannot change keeps its hash, so the map can find it later.

  10. What does this program print? public class Q5 { public static void main(String[] args) { M a = new M(1); M b = a; b = b.plus(2); System.out.println(a.value + " " + b.value); } } class M { final int value; M(int value) { this.value = value; } M plus(int amount) { return new M(value + amount); } }

    Answer

    1 3

    plus returns a new object, which b takes; a still points at the old one.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev