Immutability and defensive copying

immutable data type; has the property that the value of an object never changes once constructed.

In Java, we can enforce immutability with the final modifier. When declaring a variable as final, we are promising to assign it a value only once.

What’s the point of immutable types?

the value does not change.

prevents accidental changes.

makes programs easier to debug.

Generally, immutable types are easier to use and harder to misuse than mutable types because the scope of code that can change their values is far smaller. It is easier to debug code that uses immutable types because it is easier to guarantee that variables in client code that uses them remain in a consistent state. When using mutable types, we are always concerned about where and when their values change.

There are a few manageable downsides of immutability:

a new object must be created for every value.

final doesn’t guarantees immutability on reference types.

If an instance variable of a reference type has the final modifier, the reference will never change but the value of the object itself can change.