3 Reasons Why You Should Use Immutable Classes
An immutable class is a class whose internal state cannot be modified. The Java language contain many immutable classes, such as String, boxed primitive classes, BigInteger, and BigDecimal.
1. Immutable objects are simple
An immutable object can be in exactly one state, the state in which it was created. If you ensure all constructors establish class invariants, then these invariants will be true at all times. Mutable objects, on the other hand, can have arbitrarily complex state spaces. If the documentation does not provide a precise description of state transitions, it can be difficult or impossible to reason about the mutable class reliably.
2. Immutable objects make great building blocks
The invariant of a complex object is much easier to maintain if you know that its component objects are immutable. Immutable objects therefore, make great map keys and set elements, you don’t have to worry about their values changing once they are in the map or set, which would destroy the map or set’s invariants.
3. Immutable objects are thread-safe
Immutable objects cannot be corrupted by multiple threads accessing them concurrently. This is the easiest approach to achieve thread safety. Since no thread can observe any effect of another thread on an immutable object, immutable objects can be shared freely.