Sobes.tech
Junior — Middle

Is it possible to modify data declared as immutable?

sobes.tech AI

Answer from AI

Data declared as immutable (for example, using the final keyword in Java) cannot be changed after the reference or value is initialized. However:

  • If final is applied to a primitive type, the value cannot be changed.
  • If final is applied to an object, the reference to the object cannot be changed, but the internal state of the object can be modified if the class is not fully immutable.

Example:

final List<String> list = new ArrayList<>();
list.add("item"); // allowed, the contents of the object are modified
// list = new ArrayList<>(); // error, the reference cannot be changed

To fully protect data from modifications, you should use immutable classes or collections, such as Collections.unmodifiableList.