Java Reference
In-Depth Information
for (i = 1; i <= 10; i += 2) {
// ...
}
This latter solution can be more robust in the event of changes to the iteration con-
ditions. However, this approach should never replace careful consideration regarding the
intended and actual number of iterations.
Noncompliant Code Example
Aloopexpressionthattestswhetheracounterislessthanorequalto
Integer.MAX_VALUE
or greater or equal to
Integer.MIN_VALUE
will never terminate because the expression
will always evaluate to
true
. For example, the following loop will never terminate be-
cause
i
can never be greater than
Integer.MAX_VALUE
:
for (i = 1; i <= Integer.MAX_VALUE; i++) {
// ...
}
Compliant Solution
The loop in this compliant solution terminates when
i
is equal to
Integer.MAX_VALUE:
for (i = 1; i < Integer.MAX_VALUE; i++) {
// ...
}
If the loop is meant to iterate for every value of
i
greater than 0, including
In-
teger.MAX_VALUE
, it can be implemented as follows:
i = 0;
do {
i++
// ...
} while (i != Integer.MAX_VALUE);