Command Palette

Search for a command to run...

Back to the lesson: Topic 4.11 — Immutable Objects
Core Java · Example 1 of 3

Shared mutable price vs shared immutable price

An immutable object can't change after it's constructed: every "change" returns a new object. Immutable objects are simple to reason about, safe to share between threads, and safe as HashMap keys, which is why String, Integer, LocalDate and records are built that way.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write an immutable final class Temperature with a double celsius field, a plus(double delta) method returning a new object, and toString(). Show that the original is unchanged after plus.

02

Write an immutable final class Playlist holding a List<String> songs with a defensive copy in and an unmodifiable list out, plus withSong(String s) that returns a new playlist. Prove the original doesn't change.

03

Show that String methods return new objects: call concat, replace and trim on " hi " and print the original afterwards between brackets.

Explain it without notes

01

List the rules for making a class immutable and explain the reason for each.

02

Why isn't final enough to make an object immutable?

03

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

04

Why are immutable objects thread-safe, and what condition must hold for that guarantee?

Shared mutable price vs shared immutable price
Sign in to run this example in your browser.

Expected output

mutable:   A=80 B=80
immutable: original=100 discounted=80
String: s=chai t=CHAI