Use Enhanced For Loop
ID |
java.use_enhanced_for |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
efficiency |
Description
Reports traditional indexed for loops that iterate sequentially over an array (.length) or collection (.size()) and could be replaced with an enhanced for-each loop.
Rationale
Traditional indexed for-loops like for (int i = 0; i < array.length; i++) are verbose and error-prone: the loop variable can be misused, off-by-one errors are common, and the intent is less clear. When the loop simply iterates over every element in order, the enhanced for-each syntax is cleaner and eliminates the index variable.
// Bad — verbose indexed loop
String[] names = getNames();
for (int i = 0; i < names.length; i++) {
process(names[i]);
}
List<Item> items = getItems();
for (int i = 0; i < items.size(); i++) {
handle(items.get(i));
}
Remediation
Use the enhanced for-each loop when you only need sequential access to each element and do not need the index itself:
// Good — enhanced for-each
for (String name : names) {
process(name);
}
for (Item item : items) {
handle(item);
}
If the index is needed for more than just element access (e.g., logging position, modifying elements in place, skipping elements), the traditional indexed loop remains appropriate.