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 due to following characteristics :
- Immutable objects are simple to use test and construct.
- Immutable objects are automatically thread-safe.
- Immutable objects do not require a copy constructor.
- Immutable objects do not require an implementation of clone.
- Immutable objects allow hashCode to use lazy initialization, and to cache its return value.
- Immutable objects do not need to be copied defensively when used as a field.
- Immutable objects are good Map keys and Set elements (Since state of these objects must not change while stored in a collection).
- Immutable objects have their class invariant established once upon construction, and it never needs to be checked again.
Immutable objects always have “failure atomicity” (a term used by Joshua Bloch) if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state