Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: many grammar fixes; clarified intent of the guideline.

Programmers sometimes misconstrue that declaring a variable final makes the referenced object immutable. If When the variable is a primitive type, declaring it final means that its value cannot be changed after initialization (other than through the use of the unsupported sun.misc.Unsafe class).

However, if when the variable refers to a mutable object, the object's members that appear to be immutable, may in fact be mutable. Similarly, a final method parameter obtains a copy of the object reference through pass-by-value but the referenced data remains mutable.

...

When an object reference is declared final, it signifies only signifies that the reference cannot be changed, whereas ; the referenced contents can still be altered.

Compliant Solution (final Fields)

If When x and y must remain immutable after their initialization, they should be declared as final. However, this requires the elimination of the setter method set_xy().

...

Code Block
bgColor#ccccff
private static final String[] items = { ... };

public static final String[] somethings() {
  return items.clone();
}

As a resultConsequently, the original array values cannot be modified by a client. Note that sometimes, a manual deep copy may be required when dealing with arrays of objects. This generally happens when the objects do not export a clone() method. Refer to guideline FIO00-J. Defensively copy mutable inputs and mutable internal components for more information.

...