English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Java, an immutable class is a class whose content cannot be changed once it is created. On the same concept, an immutable object is an object whose state cannot be changed once it is constructed.
Wrapper classes become immutable due to the following advantages-
Since the state of the immutable object cannot be changed once it is created, they are automatically synchronized. Immutable objects are automatically thread-safe, thus avoiding the overhead caused by synchronization.
Once the state of the immutable object of the wrapper class is created, it cannot be changed, so they cannot enter an inconsistent state.
References to immutable objects can be easily shared or cached without copying or cloning them, because their state cannot be changed after construction.
The best use of wrapper class as an immutable object is as a key in a map.
Similarly, due to the immutability of wrapper class instances, the purpose of caching is to promote sharing. Therefore, if there are several places in your application where you need to set the value of Integer instances to42then only one instance can be used.
class Demo { public static void main(String[] args) { Integer i = new Integer(20); //initialize an object of Integer class with value as 20. System.out.println(i); operate(i);// method to change value of object. System.out.println(i); //value doesn't change shows that object is immutable. } private static void operate(Integer i) { i = i + 1; } }
Output Result
20 20