How does the final
keyword not make a variable immutable? Wikipedia says it doesn't.

- 80,077
- 70
- 264
- 372
6 Answers
In Java, the term final refers to references while immutable refers to objects. Assigning the final
modifier to a reference means it cannot change to point to another object, but the object itself can be modified if it is mutable.
For example:
final ArrayList<String> arr = new ArrayList<String>();
arr.add("hello"); // OK, the object to which arr points is mutated
arr = null; // Not OK, the reference is final and cannot be reassigned to
As the Wikipedia article mentions, if you are coming from C++, you must dissociate the concept of const
into final
and immutable.

- 171,072
- 38
- 269
- 275
Although it's not recommended, Java allows final variables to be modified using reflection.

- 87,612
- 17
- 125
- 175
Suppose you have declared that myList is final. You can still add new items to myList, so its state is NOT immutable. What you can't do, because of the final keyword, is to change myList to refer to a different list.

- 806
- 7
- 10
Read the rest of the Wikipedia article:
To illustrate that finality doesn't guarantee immutability: suppose we replace the three position variables with a single one: public final Position pos; where pos is an object with three properties pos.x, pos.y and pos.z. Then pos cannot be assigned to, but the three properties can, unless they are final themselves.

- 27,873
- 3
- 67
- 84
because if a reference is final, you can still change things in the object to which the reference points. You just cant change the reference.

- 118,147
- 33
- 203
- 236
For primitives such as int, double, char
etc it works more as you might expect.
private final int status = 10;
status = 20; // WONT COMPILE because status is final

- 1,778
- 15
- 29