Immutable Objects in Java

By | April 19, 2014

What are Immutable Objects in Java  ?
It is a very common interview question. You can expect this question in the interviews of most of good companies.Most of the times a person has used immutable objects but is not aware of the basic concepts.Here I’m writing few common interview questions which revolve around Immutable.

What is Immutable object?
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object.For ex – String class is immutable in java. What that means is , when you do some operation on a string instance to modify like strrev .A new string is created and your object now refers to that.

How to write Immutable class in java ?
Here are a few rules which should be statisfied when writing immutable class :
1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class

Here is a simple immutable java class:

You can see clearly that an object of this class cann’t be modified once created.

What are the advantages of Immutable classes in java?
1.Immutable objects are thread safe.They can be used without external synchronisation.
2.Reusability immutable objects can be cached and reused because they are immutable.
3.Immutable objects can improve performance of java code by reducing synchronization overhead.

Is it necessary that all the fields of an Immutable class should be final?
This is also a very good interview questions.Most of the times candidates are aware of the concept but they answer this question without thinking and goes against them.So what’s the answer :
The answer is NO.And this can be achieved by having few member variables as private, and exposing no other method to modify them.Here’s an exmaple:

One thought on “Immutable Objects in Java

  1. Pingback: How HashMap works in java | CrackDInterview

Leave a Reply

Your email address will not be published. Required fields are marked *