Affects PMD Version: 7.22.0
Rule:ForLoopCanBeForeach
Description:
The rule ForLoopCanBeForeach fails to detect that a traditional for loop can be replaced by an enhanced foreach loop when the array length is assigned to a pre-declared local variable before the loop starts.
Code Sample demonstrating the issue:
public class PMD_FN_Demo {
/**
* Scenario A: Standard index traversal (PMD reports this correctly)
* Violation: "This for loop can be replaced by a foreach loop"
*/
public void testTruePositive(long[] counts) {
double total = 0;
for (int i = 0; i < counts.length; i++) {// <-reported(TP)
total += counts[i];
}
}
/**
* Scenario B: Array length assigned to a pre-declared variable (FN - PMD misses this)
* Even though it is semantically identical to Scenario A, no violation is reported.
*/
public void testFalseNegative(long[] counts) {
double total = 0;
// Assigning array length to a pre-declared local variable
int len = counts.length;
for (int i = 0; i < len; i++) {//<-should report (FN)
total += counts[i];
}
}
}
Expected outcome:
PMD should report a violation at line 22 , but doesn't. This is a false-negative.
Running PMD through: CLI
Affects PMD Version: 7.22.0
Rule:ForLoopCanBeForeach
Description:
The rule ForLoopCanBeForeach fails to detect that a traditional for loop can be replaced by an enhanced foreach loop when the array length is assigned to a pre-declared local variable before the loop starts.
Code Sample demonstrating the issue:
Expected outcome:
PMD should report a violation at line 22 , but doesn't. This is a false-negative.
Running PMD through: CLI