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
| Property | Mutable | Immutable |
|---|---|---|
| State after creation | Can change | Cannot change |
| Result of a change | The same object is updated | A new object is created |
| Examples | StringBuilder, ArrayList | String, Integer, LocalDate |
| Sharing a reference | Anyone holding a reference may see changes | No 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);8
5
skaiciusinitially stores the value5.kopija = skaiciuscopies the numeric value itself.skaicius = 8assigns a different value to the variable; the number5was not “changed into”8.kopijaremains5because primitive variables do not share one mutable object.
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());3
- The object is created with two products.
- The method
pridetiProdukta()changes the same object's attribute. - A new
PirkiniuSarasasobject is not created. - 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());18.0
22.0
- The class is marked
finaland its attribute isprivate final. - Object
ryteis created with the value18.0. padidinti()does not change the existing object: it returns a newTemperatura.- Therefore,
ryteremains18.0, whiledienahas22.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());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);Labas
Labas rytas
Labas rytas
String.concat()does not changetekstas; the method returns a newString.StringBuilder.append()changes the actualStringBuildercontents.- 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);Labas
LABAS
10
15
toUpperCase() does not change the original String. Arithmetic with Integer also produces another value without changing the original object.
| Class or group | Why is immutability useful? |
|---|---|
String | Text can be safely shared, used as a collection key and reused from the string pool. |
Integer, Long, Double, Boolean, Character | Primitive wrapper objects behave as stable values. |
BigInteger and BigDecimal | Each arithmetic method returns a new precise number without changing the original. |
LocalDate, LocalTime, LocalDateTime, Duration | Date and time calculations do not change existing dates, making results easier to track. |
UUID | The identifier's value stays stable after creation. |
Optional | The container's state stays unchanged; operations return another result. |
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
StringBuilderandStringBufferchanges the character sequence being built.ArrayList,HashSetandHashMapallow elements to be added, removed or replaced.- Arrays, for example,
int[]have fixed lengths, but their elements can be changed. - Older date classes,
DateandCalendar, are mutable; the newerjava.timeclasses 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?
| Choose immutable when | Choose mutable when |
|---|---|
| the value must be stable and predictable | the object's state naturally changes often |
| different program parts or threads share the object | many changes must be performed efficiently |
the object is used as a HashMap key | you are building a buffer, accumulator or editable model |
| minimizing unexpected side effects matters | the 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.