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
- Immutable
objects are thread-safe so you will not have any synchronization issues.
- Immutable
objects are good Map keys and Set elements,
since these typically do not change once created.
- Immutability
makes it easier to write, use and reason about the code (class invariant
is established once and then unchanged)
- Immutability
makes it easier to parallelize your program as there are no conflicts
among objects.
- The
internal state of your program will be consistent even if you have
exceptions.
- 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 :) :) :)
Thanks
Neeraj Srivastava
Java Developer
Happy Learning :) :)
Keep Smiling :) :) :)
No comments:
Post a Comment