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, from within the loop body.

Noncompliant Code Example

This noncompliant code example attempts to initialize a Character array using an enhanced for loop. However, because assignments to the loop variable do not modify the array over which the loop iterates, the array is not suitably initialized.

...

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

Compliant Solution

This compliant solution correctly initializes the array using a for loop.

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

for(final Character c: array) 
  System.out.print(c);  // prints 10 "x" 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.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL30- J

low

unlikely

low

P3

L3

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

TODO

References

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] Section [14.14.2|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] "The enhanced for statement"

...