Skip to content
Tutorials Center
My learning

Topics

Lesson 53 of 201 ยท Object-Oriented Programming

Immutable Classes

Learn how to write immutable classes in Java - final fields, no setters, defensive copies, with-methods - why they're safer for maps and threads, and records.

An immutable object can't change after it's created. Its fields are set once, in the constructor, and stay that way until the object is garbage collected. Any "change" produces a new object and leaves the original untouched. You've already used immutable objects all the time: every String, Integer and LocalDate works this way.

That sounds like a restriction, and it is one, but it removes whole categories of bugs. An immutable object can't be corrupted by a caller, can't change while it sits in a HashSet, and can be shared between threads with no locks at all. This lesson shows the recipe for an immutable class, the mistakes that quietly break it, why it pays off, and how records give you most of it in one line.

Immutable objects you already know

String methods that sound like they modify the string actually return a new one. The same holds for the date and time classes in java.time:

Java Strings and dates never change in place

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first line prints lisbon, not LISBON. Calling a "changing" method and ignoring the result is a classic beginner bug with immutable types; the fix is always to use the returned object. Many IDEs warn about it.

The recipe

A class is immutable when no code, inside or outside it, can change its observable state after construction. In practice that means five rules:

  1. Make all fields private and final. final means each field is assigned exactly once, and the compiler checks it.
  2. Don't provide setters or any other method that changes a field.
  3. Prevent subclassing. Declare the class final (or make all constructors private and offer static factories). Otherwise a subclass could add mutable state or override methods to lie about the values.
  4. Copy mutable inputs in the constructor, so the caller can't change them afterward.
  5. Never hand out mutable internals. Return copies or unmodifiable views, or better, store only immutable types.

Instead of setters, immutable classes offer methods that return a modified copy. They're often named withX ("with a different X") or after the operation (plus, scaled):

Java An immutable Money class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Money never changes, so price still prints 19.99 EUR at the end, no matter how many calculations used it. Validation happens once, in the constructor, and every new Money goes through that constructor, so an invalid Money can't exist. (Real money code would also use BigDecimal or a library; see BigInteger and BigDecimal.)

final fields are not enough

The most common way to get immutability wrong is to make fields final and stop there. final freezes the reference, not the object it points to. If a field holds a mutable List, array or StringBuilder, the contents can still change:

Java A final field pointing at a mutable list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

BrokenTeam prints [Ben, Intruder]: changed twice, from two directions. Team copies the input with List.copyOf, which produces an unmodifiable list. Because that list can't change, the getter can return it directly with no further copying. Storing immutable values internally is always simpler than copying on every get.

Watch out for these mutable types inside "immutable" classes: arrays (always mutable; clone them both ways), ArrayList/HashMap and friends, StringBuilder, legacy java.util.Date and Calendar, and your own mutable classes. Also note that List.copyOf is only shallow: a list of immutable strings is fully frozen, but a list of mutable objects still contains objects that can change.

Why the class must be final

If Money weren't final and had a non-private constructor, someone could write this:

Java
class SneakyMoney extends Money {      // impossible with the real Money
    private long fakeCents;
    SneakyMoney() { super(0, "EUR"); }
    void set(long cents) { fakeCents = cents; }

    @Override
    public String toString() { return fakeCents + " (lies)"; }
}

Any method that accepts a Money could then receive a SneakyMoney whose behavior changes over time, and every guarantee you built would be gone. final class (or private constructors only) closes that door. You'll learn the details of extending classes in Inheritance.

Why immutability helps

Safe keys in maps and sets

HashSet and HashMap file each object under a bucket chosen by its hashCode() at the moment it's inserted. If the object's fields change afterward, its hash code changes, and the set looks in the wrong bucket. The object is still inside, but it can't be found:

Java A mutable key gets lost in a HashSet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

After the change, contains(p) returns false even though the set's size is 1 and printing it shows (99, 2). The object is stuck in the bucket for its old hash code. With immutable keys this simply can't happen; that's why String, Integer and records make ideal map keys. How HashMap Works Inside explains buckets in depth.

Thread safety for free

Most concurrency bugs come from one thread changing data while another reads it. An immutable object can't change, so any number of threads can read it at once without synchronized or locks. Java also gives final fields a special guarantee: once the constructor finishes, every thread that gets a reference to the object sees the final fields fully initialized. (That guarantee breaks if this escapes from the constructor, which is one more reason not to let it; see The this Keyword.) Synchronization and Race Conditions shows what goes wrong without it.

Simpler reasoning and free sharing

  • No surprises. When you pass an immutable object to a method, you know it comes back unchanged. No defensive copies are needed on the way in or out.
  • Safe sharing and caching. Two parts of a program can share one instance. Integer.valueOf(42) returns a cached object, and String literals are shared in the string pool, only because they can't change.
  • Failure atomicity. If a method on an immutable object throws, nothing was half-modified; the original is exactly as it was.
  • Valid forever. Check the rules once in the constructor, and the object stays valid for its whole life.

Records: immutability the easy way

A record is a class designed to be a transparent, immutable data carrier. One line gives you private final fields, a constructor, accessor methods, equals, hashCode and toString. Records are implicitly final and have no setters. Add a compact constructor for validation and defensive copies:

Java An immutable record with validation and a defensive copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compact constructor runs before the fields are assigned, and reassigning the parameter stops changes what gets stored. Records are shallowly immutable, just like a hand-written class with final fields: a record component of a mutable type still needs the copy shown here. For plain data, a record is now the default choice; write a full class when you need to hide the representation or control construction more tightly.

The cost, and how to manage it

Creating a new object for every change costs allocations. For most code that's negligible: the JVM allocates short-lived objects very cheaply, and the garbage collector is built for them. When it does matter, for example building a long string in a loop, use a mutable companion for the construction phase and freeze the result at the end. StringBuilder is the companion of String; builders play that role for complex objects (Creational Design Patterns).

Also keep two words apart:

  • Immutable: the object can't change, ever, for anyone (List.of(...), String).
  • Unmodifiable view: you can't change it through this reference, but the underlying data might still change (Collections.unmodifiableList(list)). See Immutable Collections and Utility Methods.

And final is not the same as immutable: a final variable can point to a mutable object. The final Keyword Everywhere compares them side by side.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? String s = "hi"; s.concat(" there"); IO.println(s);

    Strings are immutable. concat returns a new string, which is discarded here, so s still refers to "hi".
  2. 2. A final class has private final int[] scores; assigned directly from a constructor parameter and returned directly by a getter. Is it immutable?

    final only fixes the reference. The array itself can still be modified. Clone it in the constructor and in the getter, or store an immutable List instead.
  3. 3. Why should an immutable class be declared final (or have only private constructors)?

    A subclass instance can be passed wherever the parent type is expected. If it can change, every guarantee the parent made is void.
  4. 4. You put a mutable object into a HashSet, then change a field used by its hashCode. What does contains(thatObject) usually return?

    The object was filed under its old hash code. After the change, lookups go to a different bucket, so the set can't find it even though it's still inside.
  5. 5. In record Tags(List<String> list) { Tags { list = List.copyOf(list); } }, what does the compact constructor achieve?

    Records are only shallowly immutable. Reassigning the parameter in the compact constructor changes what is stored, so the record keeps its own unmodifiable copy.

Summary

  • An immutable object never changes after construction; "modifying" methods return new objects, and their results must be used.
  • Recipe: private final fields, no setters, a final class (or private constructors), copy mutable inputs, never expose mutable internals.
  • final freezes references, not objects; arrays and collections inside need copies (List.copyOf, clone()), and copies are shallow.
  • Immutable objects make safe HashMap/HashSet keys, can be shared across threads without locks, can be cached, and stay valid forever.
  • Records are concise, final, shallowly immutable classes; use a compact constructor to validate and copy.
  • Use a mutable companion such as StringBuilder or a builder when many changes would create too many objects.

Next: Static Fields, Methods and Blocks, where you'll see what belongs to a class as a whole rather than to each object.