Search code examples
javaimmutabilityfinal

Java final keyword for variables


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


Solution

  • 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.