You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 2 Next »

The enhanced for statement introduced in Java 1.5, commonly referred to as the for-each idiom, finds primary application in iterating over collections of objects. While similar to the usual for statement, this idiom cannot be used to assign values or initialize data.

Noncompliant Code Example

The intention behind this noncompliant example is to initialize a Character array using a for-each idiom. Unbeknownst to the developer, the array is not suitably initialized. This is because it is impossible to carry out assignments from within a for-each loop.

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]);	  

Compliant Solution

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

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

Risk Assessment

Attempts to initialize data from within the enhanced for loop (for-each idiom) will be futile and will 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

[[JLS 05]] 14.14.2 "The enhanced for statement"


DCL06-J. Beware integer literals beginning with '0'.      01. Declarations and Initialization (DCL)      01. Declarations and Initialization (DCL)

  • No labels