Immutability in Java

Immutability means something that is not changeable and there is no way in which you can change the state/behavior of the object once it has been created in the heap.

All the variables in Java are mutable by default.

The most typical question asked in the interviews these days, is, how can you make an object immutable?


The answer is:

  1. By making the class final. Object should be final in order to restrict sub-class for altering immutability of parent class.
  2. Making the fields final and private and no public access to the outside world must be provided.
  3. Do not provide setter methods, that can change the state the object.
  4. Need to handle carefully the mutable instance variables inside the immutable class that you are creating.

As you go through the example below, kindly check the comments as well for better understanding.

We can see that there is a mutable field for Date in our class. But let’s test if we have handled it properly.

Output:
jCombat 999999999 Sun Sep 21 11:32:39 IST 2014
jCombat 999999999 Sun Sep 21 11:32:39 IST 2014

We can see that, inspite of trying change the date in line number 4, the actual object state hasn’t changed.

Below are the main advantages of immutable objects:

  1. Thread safety, as immutable objects can easily be shared without synchronization in concurrent environment.
  2. You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret behind Java’s very fast substring implementation.You can share duplicates by pointing them to a single instance.
  3. Imagine using a mutable type as Hashtable key; if a reference to one of these mutable objects is used as a key, its hash value is computed and then it is put into one of my Hashtable buckets. But if this object is later modified, there is no way to be notified; and the object may now reside in the wrong bucket (if its hash value is different). Therefore, Hashmap keys need to have immutable objects as their keys.
  4. Mutable string can cause security issues. Below mentioned scenario would make this point clear to you.

NOTE:

  1. The wrapper classes, Byte, Character, Short, Integer, Long, Float and Double are all immutable.
  2. Strings are immutable, though the references to them are mutable. StringBuffers are mutable.

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.