Tutorials

Google+ Followers

What is immutable object in Java? Can you change values of a immutable object?How Immutable objects simplify your program?

A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit.

Immutable objects simplify your program, since they :

1.are simple to use test and construct.2.are automatically thread-safe.3.do not require a copy constructor.4.do not require an implementation of clone.5.allow hashCode to use lazy initialization, and to cache its return value.6.do not need to be copied defensively when used as a field.7.are good Map keys and Set elements (these objects must not change state while stored in the collection).8.have their class invariant established once upon construction, and it never needs to be checked again.