Immutable objects
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Some objects can never change once they exist. String is the best-known one, and this idea, immutability, makes objects safe to share, pass around and use as keys.
An immutable object never changes
An immutable object is an object whose state, the values of its fields, can never change after it is created. String and the wrapper classes such as Integer are immutable: a method that seems to change one returns a new object instead.
You met this in String transformation methods (opens in a new tab): upi.trim(); builds a new string and throws it away. Only upi = upi.trim(); keeps it.
Example 1 · String methods return a new string
public class StringDemo { public static void main(String[] args) { String upi = " kavya@okaxis "; upi.trim(); upi.toUpperCase(); System.out.println("[" + upi + "]");
String clean = upi.trim().toUpperCase(); System.out.println("[" + clean + "]"); System.out.println("[" + upi + "]"); }}[ kavya@okaxis ] [KAVYA@OKAXIS] [ kavya@okaxis ]
What this code does
upi.trim();andupi.toUpperCase();each made a new string and threw it away;upiis unchanged.- Storing the result in
cleankeeps the new string. The original object still has its spaces.
Every String method works this way: concat, replace, trim, substring. StringBuilder (opens in a new tab) is the mutable (changeable) partner: sb.append("x") changes the same object.
name.trim(); on its own line, is a very common bug. The line compiles and does nothing.The variable can change, the object cannot
Two different things can "change": the variable (which object it points to) and the object (its fields). Immutability is about the object. final is about the variable.
Example 2 · Sharing a String vs sharing a StringBuilder
public class SharingDemo { public static void main(String[] args) { String a = "Aarav"; String b = a; a = a + " Shah"; System.out.println(a + " | " + b);
StringBuilder x = new StringBuilder("Aarav"); StringBuilder y = x; x.append(" Shah"); System.out.println(x + " | " + y); }}Aarav Shah | Aarav Aarav Shah | Aarav Shah
What this code does
a + " Shah"creates a new string and moves onlya;bstill points to the old, unchanged"Aarav".appendchanges the oneStringBuilderobject, so bothxandysee the change.
Example 3 · final variable vs immutable object
public class FinalDemo { public static void main(String[] args) { final int[] marks = { 70, 80 }; marks[0] = 95; System.out.println(marks[0] + ", " + marks[1]);
final StringBuilder note = new StringBuilder("Exam"); note.append(" on Monday"); System.out.println(note);
String city = "Pune"; city = city.replace("P", "R"); System.out.println(city); }}95, 80 Exam on Monday Rune
What this code does
finalonly stops the variable from pointing elsewhere; the array and theStringBuilderobjects still change.cityis notfinal, so it can point to a new string, but noStringobject was ever changed.
s = s + "!" changes no string: it makes a new one and moves the variable. A final variable, as in final variables (opens in a new tab), can never move, yet the array or StringBuilder it points to may still change. So final does not mean immutable.
Trace the code
Variables move, objects stay
Variables
- city
- "Pune"
Output
(nothing printed yet)Line 3city points to a String object "Pune".
Why immutability helps
Many variables can share one immutable object, and none of them can spoil it for the others. With a mutable object, one change is seen by everyone who shares it.
Example 4 · Mistake: a shared mutable object changes for everyone
class Fee { int amount;
Fee(int amount) { this.amount = amount; }}
class Student { String name; Fee fee;
Student(String name, Fee fee) { this.name = name; this.fee = fee; }}
public class SharedFeeDemo { public static void main(String[] args) { Fee standard = new Fee(45000); Student priya = new Student("Priya", standard); Student rohan = new Student("Rohan", standard);
rohan.fee.amount = rohan.fee.amount - 5000; System.out.println("Rohan pays Rs. " + rohan.fee.amount); System.out.println("Priya pays Rs. " + priya.fee.amount); }}Rohan pays Rs. 40000 Priya pays Rs. 40000
What this code does
- Both students point to the same mutable
Feeobject, so Rohan's discount also changed Priya's fee. - If
Feewere immutable, a discount would have to create a newFeefor Rohan, and Priya's fee would be safe.
An immutable object is also safe to pass to any method, stays valid once its constructor has checked it, and keeps a stable hashCode(). That matters when it is used as a key, a value used to look things up: a key that changed could no longer be found.
Wrapper classes are immutable too
A wrapper class holds one primitive value inside an object: Integer for int, Double, Boolean, Character and others. Integer n = 5; works through autoboxing, and every wrapper object is immutable.
Example 5 · Integer is immutable
public class WrapperDemo { static void addBonus(Integer runs) { runs = runs + 10; System.out.println("Inside method: " + runs); }
public static void main(String[] args) { Integer a = 50; Integer b = a; a++; System.out.println("a = " + a + ", b = " + b);
Integer score = 80; addBonus(score); System.out.println("After method: " + score); }}a = 51, b = 50 Inside method: 90 After method: 80
What this code does
a++creates a newInteger51 and movesa;bstill points to the old 50.- Inside
addBonus,runs = runs + 10only moves the parameter to a newInteger; the caller'sscoreis untouched.
So n++ on an Integer makes a new Integer and moves n. Immutability has a cost: every change is a new object. To build long text in a loop, use a StringBuilder, then make one String at the end.
Next step
Check your understanding
12 quick questions