Junior — Middle
Is it possible to change the value of a variable declared as effectively final inside an object?
sobes.tech AI
Answer from AI
In Java, the term "effectively final" means that a variable has not been changed after initialization, although it is not explicitly declared with the final keyword. This is important, for example, when using such variables in lambda expressions or anonymous classes.
If a variable is declared as effectively final, its value cannot be changed — attempting to assign a new value will result in a compile-time error.
However, if this variable references an object, the state of the object itself can be modified, since the reference does not change, only the internal fields of the object. For example:
final List<String> list = new ArrayList<>();
list.add("new item"); // This is allowed
// list = new ArrayList<>(); // Error, cannot change the reference
Thus, the variable's reference cannot be changed, but the contents of the object it points to can be modified.