In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.[1] This is in contrast to a mutable object, which can be modified after it is created.
Immutable objects are often useful because they are inherently thread-safe.[1] Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.[1]
Small immutable objects can easily be copied efficiently, but larger immutable objects require more complicated persistent data structure algorithms to be efficiently copied. Mutable objects are sometimes used instead of immutable objects for performance reasons.
Python
In Python, some built-in types (numbers, strings, tuples, frozensets) are immutable, but custom classes are generally mutable.
Java
A classic example of an immutable object is an instance of the Java String
class.
String s = "ABC"; s.toLowerCase();
The method toLowerCase()
will not change the data "ABC" that s
contains. Instead, a new String object is instantiated and given the data "abc" during its construction. A reference to this String object is returned by the toLowerCase()
method. To make the String s
contain the data "abc", a different approach is needed.
s = s.toLowerCase();
Now the String s
references a new String object that contains "abc". There is nothing in the syntax of the declaration of the class String that enforces it as immutable; rather, none of the String class's methods ever affect the data that a String object contains, thus making it immutable.