The enhanced for
statement introduced in Java 1.5, commonly referred to as the for-each idiom, is primarily used for iterating over collections of objects. While similar to the for
statement, this idiom cannot be used to assign values to the loop variable.
Noncompliant Code Example
This noncompliant example attempts to initialize a Character
array using an enhanced for
loop. However, because the loop variable cannot be assigned to, the array is not suitably initialized.
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
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'; for(int i=0;i<array.length;i++) System.out.print(array[i]); // prints 10 "x"s
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
[[JLS 05]] Section 14.14.2 "The enhanced for statement"
DCL08-J. Enforce compile-time type checking of variable argument types 02. Declarations and Initialization (DCL) DCL31-J. Qualify mathematical constants with the static and final modifiers