Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Addressed the comments, updated the references to Java 7 and changed to Applicability

...

Programmers often incorrectly assume that declaring a field or variable final makes the referenced object immutable. Declaring variables that have a primitive type to be final does prevent changes to their values after initialization (unless the unsupported sun.misc.Unsafe class is usedby normal Java processing). However, when the variable has a reference type, the presence of a final clause in the declaration only makes the reference itself immutable. The final clause has no effect on the referenced object. Consequently, the fields of the referenced object can may be mutable. For example, according to the Java Language Specification [JLS 20052011], §4.12.4, "final Variables","

If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

This applies also to arrays, because arrays are objects; if If a final variable holds a reference to an array, then the components of the array may be changed by operations on the array, but the variable will always refer to the same array.

...

Neither the original array values nor the public list can be modified by a client. For more details about unmodifiable wrappers, refer to SEC57-J. Provide sensitive mutable classes with unmodifiable wrappers. This solution can also be used when the array contains mutable objects.

...

Applicability

Incorrectly assuming that final references cause the contents of the referenced object to remain mutable can result in an attacker modifying an object thought by the programmer to be immutable.

...

[Bloch 2008]

Item 13: Minimize the accessibility of classes and members

[Core Java 2004]

Chapter 6

[JLS 20052011]

§4.12.4, "final Variables"

 

§6.6, "Access Control"

[Mettler 2010B]