Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

It is recommended that all enhanced for statement loop variables be declared final. The final declaration causes Java compilers to flag and reject any assignments made to the loop variable, in from within the loop body.

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
Character[] array = new Character[10];
for(Character c: array) 
  c = 'x'; // initialization attempt

for(int i=0;i<array.length;i++) 
  System.out.print(array[i]);  // prints 10 "null"s values

Note that if c is declared final, a compiler error results when an attempt is made to initialize it.

...

Code Block
bgColor#ccccff
Character[] array = new Character[10];
for(int i = 0;i<array i < array.length; i++) 
  array[i] = 'x';

for(final Character c: array) 
  System.out.print(c);  // prints 10 "x"s values

Risk Assessment

Attempts to assign to the loop variable from within the enhanced for loop (for-each idiom) are futile and may leave the class in a fragile, inconsistent state.

...