Equality In Loop Termination Condition
ID |
java.equality_in_loop_condition |
Severity |
high |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Java |
Tags |
control-flow, loop, reliability |
Description
Reports a classic for loop whose termination condition tests the counter with == or != instead of a relational operator. If the step ever overshoots the target value, the equality is never satisfied and the loop runs forever.
The comparison is not reported when the counter is left alone in the loop body and the for-header update advances it by exactly one unit (++, --, += 1 or -= 1): a single-unit step can never skip past an integer target, so != is as safe as a relational operator in that case. A comparison against null (the idiomatic array or list walk) and a condition that assigns as part of the test are both left alone as well, matching how those shapes are normally written.
Rationale
A relational operator (<, ⇐, >, >=) tolerates the counter stepping past the boundary in one jump; equality does not. A step introduced later — doubling an increment for performance, adding a continue path that skips ahead — silently turns a working loop into a hang, and the failure only shows up at runtime.
for (int i = 1; i != 10; i += 2) { // i goes 1, 3, 5, 7, 9, 11, 13, ... -- never 10
process(i);
}