Skip to lesson

Immutable objects

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

StringDemo.javaJava
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 + "]");    }}
Output
[  kavya@okaxis  ]
[KAVYA@OKAXIS]
[  kavya@okaxis  ]

What this code does

  • upi.trim(); and upi.toUpperCase(); each made a new string and threw it away; upi is unchanged.
  • Storing the result in clean keeps 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.

Forgetting to store the result, like 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

SharingDemo.javaJava
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);    }}
Output
Aarav Shah | Aarav
Aarav Shah | Aarav Shah

What this code does

  • a + " Shah" creates a new string and moves only a; b still points to the old, unchanged "Aarav".
  • append changes the one StringBuilder object, so both x and y see the change.

Example 3 · final variable vs immutable object

FinalDemo.javaJava
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);    }}
Output
95, 80
Exam on Monday
Rune

What this code does

  • final only stops the variable from pointing elsewhere; the array and the StringBuilder objects still change.
  • city is not final, so it can point to a new string, but no String object 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

public class MoveTrace {
public static void main(String[] args) {
String city = "Pune";
String home = city;
city = city.toUpperCase();
city.concat(" East");
final StringBuilder note = new StringBuilder("Bus");
note.append(" 42");
System.out.println(city + " " + home + " " + note);
}
}

Variables

city
"Pune"

Output

(nothing printed yet)

Line 3city points to a String object "Pune".

Step 1 of 7

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.

Two students share one Fee object. Mutable Fee: rohan.fee.amount is changed in place, so priya.fee and rohan.fee both see 40000. Immutable Fee: rohan.fee = rohan.fee.discount(5000) makes a new Fee of 40000 for Rohan only, and Priya still points to the unchanged Fee of 45000.

Example 4 · Mistake: a shared mutable object changes for everyone

SharedFeeDemo.javaJava
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);    }}
Output
Rohan pays Rs. 40000
Priya pays Rs. 40000

What this code does

  • Both students point to the same mutable Fee object, so Rohan's discount also changed Priya's fee.
  • If Fee were immutable, a discount would have to create a new Fee for 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

WrapperDemo.javaJava
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);    }}
Output
a = 51, b = 50
Inside method: 90
After method: 80

What this code does

  • a++ creates a new Integer 51 and moves a; b still points to the old 50.
  • Inside addBonus, runs = runs + 10 only moves the parameter to a new Integer; the caller's score is 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