Use Integer Index Variable in Loops
ID |
java.loop_integer_index |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
best-practice, reliability |
Description
Reports for-loops whose index variable is declared with a non-integer type such as long, double, or float.
Rationale
Array indices in Java must be int. Using a long index variable may cause silent truncation when used as an array index. Floating-point index variables (float, double) suffer from rounding errors that can cause off-by-one iteration counts or infinite loops.
// Bad - long index may truncate when used as array index
for (long i = 0; i < arr.length; i++) {
System.out.println(arr[(int) i]);
}
// Bad - floating-point rounding may skip or repeat iterations
for (double d = 0; d < 10; d++) {
System.out.println(d);
}