Primitive Wrapper Classes are Immutable in Java


In Java Immutable class is a class which once created and it's contents can not be changed.On same concept Immutable objects are the objects whose state can not be changed once constructed.

Wrapper classes are made to be immutable due to following advantages −

  • Since the state of the immutable objects can not be changed once they are created they are automatically synchronized.Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.

  • Once created the state of the wrapper class immutable object can not be changed so there is no possibility of them getting into an inconsistent state.

  • The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.

  • The best use of the wrapper class as immutable objects is as the keys of a map.

  • Also due to immutability of wrapper class instances the purpose of caching is to facilitate sharing. So, if you have a dozen places in your application that needed to have the Integer instance with a value of 42, then you can use only one instance instead.

Example to show wrapper class as immutable.

class Demo {
   public static void main(String[] args) {
      Integer i = new Integer(20); //initialize a 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

20
20

Updated on: 25-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements