Saturday, 21 January 2017

Immutable Class in Java

Immutable

Immutable objects are those objects whose state can not be changed once created

Ex- String, Boolean, Byte, Short, Integer, Long, Float, Double etc. Means, all the wrapper classes and String class is immutable.

Please Be careful, there is difference between final and Immutable , people always do mistake here in interviewer ask question in details.


Difference between  final & immutable 
final means that you can't change the object's reference to point to another reference. Where immutable means that actual object's value can't be changed, but you can change its reference to another one.

                                          See Concepts in Image
   



Benefits of making a class immutable
  1. Immutable objects are thread-safe so you will not have any synchronization issues.
  2. Immutable objects are good Map keys and Set elements, since these typically do not change once created.
  3. Immutability makes it easier to write, use and reason about the code (class invariant is established once and then unchanged)
  4. Immutability makes it easier to parallelize your program as there are no conflicts among objects.
  5. The internal state of your program will be consistent even if you have exceptions.
  6. References to immutable objects can be cached as they are not going to change.
If any query then make a comment

Thanks
Neeraj Srivastava
Java Developer

Happy Learning :) :)
Keep Smiling :) :) :)






No comments:

Post a Comment