VS

Immutable vs mutable Java objects

Mutable objects can change their state after creation. Immutable objects do not change state after creation: a different value requires a new object.

The main difference

Comparing mutable and immutable objects
PropertyMutableImmutable
State after creationCan changeCannot change
Result of a changeThe same object is updatedA new object is created
ExamplesStringBuilder, ArrayListString, Integer, LocalDate
Sharing a referenceAnyone holding a reference may see changesNo unexpected state changes

An object's state is its attribute values at a particular moment. For example, a shopping list's state may include the number of products it contains.

Are primitive types mutable or immutable?

The short answer: primitive types are not objects, so the object-related terms mutable and immutable do not formally apply to them. int, double, char or boolean variable stores the value itself rather than an object reference.

int skaicius = 5;
int kopija = skaicius;

skaicius = 8;

System.out.println(skaicius);
System.out.println(kopija);
Console output

8
5

  1. skaicius initially stores the value 5.
  2. kopija = skaicius copies the numeric value itself.
  3. skaicius = 8 assigns a different value to the variable; the number 5 was not “changed into” 8.
  4. kopija remains 5because primitive variables do not share one mutable object.
A variable can change without an object being mutated.

The assignment skaicius = 8 changes which value the variable stores. Mutation means changing the internal state of an existing object.

A mutable object

class PirkiniuSarasas {
    private int produktuKiekis;

    PirkiniuSarasas(int produktuKiekis) {
        this.produktuKiekis = produktuKiekis;
    }

    void pridetiProdukta() {
        produktuKiekis++;
    }

    int getProduktuKiekis() {
        return produktuKiekis;
    }
}

PirkiniuSarasas sarasas = new PirkiniuSarasas(2);
sarasas.pridetiProdukta();

System.out.println(sarasas.getProduktuKiekis());
Console output

3

  1. The object is created with two products.
  2. The method pridetiProdukta() changes the same object's attribute.
  3. A new PirkiniuSarasas object is not created.
  4. The same object later stores the value 3.

A mutable object is useful when its state naturally changes often: in a shopping cart, text-building buffer or UI element.

An immutable object

final class Temperatura {
    private final double celsijai;

    Temperatura(double celsijai) {
        this.celsijai = celsijai;
    }

    double getCelsijai() {
        return celsijai;
    }

    Temperatura padidinti(double kiek) {
        return new Temperatura(celsijai + kiek);
    }
}

Temperatura ryte = new Temperatura(18.0);
Temperatura diena = ryte.padidinti(4.0);

System.out.println(ryte.getCelsijai());
System.out.println(diena.getCelsijai());
Console output

18.0
22.0

  1. The class is marked finaland its attribute is private final.
  2. Object ryte is created with the value 18.0.
  3. padidinti() does not change the existing object: it returns a new Temperatura.
  4. Therefore, ryte remains 18.0, while diena has 22.0.

Why must mutable objects be watched more carefully?

PirkiniuSarasas pirmas = new PirkiniuSarasas(2);
PirkiniuSarasas antras = pirmas;

antras.pridetiProdukta();

System.out.println(pirmas.getProduktuKiekis());
System.out.println(antras.getProduktuKiekis());
Console output

3
3

pirmas and antras refer to the same object. Changing it through one reference makes the new state visible through the other. This is not an error, but such side effects can be surprising in larger programs.

String and StringBuilder example

String tekstas = "Labas";
String papildytas = tekstas.concat(" rytas");

System.out.println(tekstas);
System.out.println(papildytas);

StringBuilder kuriamas = new StringBuilder("Labas");
kuriamas.append(" rytas");

System.out.println(kuriamas);
Console output

Labas
Labas rytas
Labas rytas

  • String.concat() does not change tekstas; the method returns a new String.
  • StringBuilder.append() changes the actual StringBuilder contents.
  • Both approaches can produce the same text, but the objects behave differently.

Common immutable Java classes

Java has many classes whose objects cannot change after creation. Methods that look like changes usually return a new object.

String tekstas = "Labas";
String didziosiomis = tekstas.toUpperCase();

Integer skaicius = 10;
Integer didesnis = skaicius + 5;

System.out.println(tekstas);
System.out.println(didziosiomis);
System.out.println(skaicius);
System.out.println(didesnis);
Console output

Labas
LABAS
10
15

toUpperCase() does not change the original String. Arithmetic with Integer also produces another value without changing the original object.

Examples of common immutable Java classes
Class or groupWhy is immutability useful?
StringText can be safely shared, used as a collection key and reused from the string pool.
Integer, Long, Double, Boolean, CharacterPrimitive wrapper objects behave as stable values.
BigInteger and BigDecimalEach arithmetic method returns a new precise number without changing the original.
LocalDate, LocalTime, LocalDateTime, DurationDate and time calculations do not change existing dates, making results easier to track.
UUIDThe identifier's value stays stable after creation.
OptionalThe container's state stays unchanged; operations return another result.
A record is not automatically deeply immutable.

Record components cannot be assigned different references, but if a record stores a mutable List or another mutable object, its contents can still change. A defensive copy is needed.

Common mutable Java classes and types

  • StringBuilder and StringBuffer changes the character sequence being built.
  • ArrayList, HashSet and HashMap allow elements to be added, removed or replaced.
  • Arrays, for example, int[]have fixed lengths, but their elements can be changed.
  • Older date classes, Date and Calendar , are mutable; the newer java.time classes are immutable.
  • Your own classes with state-changing methods or setters are usually mutable.

Mutability is not inherently a flaw. Collections, buffers and models often need to change. What matters is knowing who can change an object and who else holds a reference to it.

How do you create an immutable class?

  • prevent unsafe subclassing, often by marking the class final;
  • attributes are private final;
  • set all values in the constructor;
  • provide no setters that change state;
  • protect mutable internal objects with copies.
import java.util.List;

final class Receptas {
    private final List produktai;

    Receptas(List produktai) {
        this.produktai = List.copyOf(produktai);
    }

    List getProduktai() {
        return produktai;
    }
}

List.copyOf() creates an unmodifiable copy of the supplied list. If the constructor simply stored the received mutable list, external code could unexpectedly change the Receptas state.

final reference does not make the object immutable.

final List<String> prevents the reference from pointing to another list, but the list itself may still be mutable. An unmodifiable or defensive copy is therefore needed.

When should you choose each?

Choosing in practice
Choose immutable whenChoose mutable when
the value must be stable and predictablethe object's state naturally changes often
different program parts or threads share the objectmany changes must be performed efficiently
the object is used as a HashMap keyyou are building a buffer, accumulator or editable model
minimizing unexpected side effects mattersthe system reasonably requires setter methods

Neither option is always better. A useful starting rule is to choose immutability when state need not change, and deliberately use mutable objects where their flexibility has a clear benefit.