Java Reference
In-Depth Information
// Intentional fall-through
// These three cases are treated identically
case 11:
// Break not required
case 12:
// Break not required
case 13:
value = 10;
break;
// Break required
default:
// Handle error condition
}
Also,whenacaseendswitha
return
or
throw
statementornonreturningmethodsuch
as
System.exit()
, the
break
statement may be omitted.
Bibliography
[JLS 2013]
§14.11, “The
switch
Statement”
57. Avoid inadvertent wrapping of loop counters
Unless coded properly, a
while
or
for
loop may execute forever, or until the counter
wrapsaroundandreachesitsfinalvalue.(See
The CERT
®
Oracle
®
Secure Coding Stand-
ard for Java
™
[Long 2012], “NUM00-J. Detect or prevent integer overflow.”) This prob-
lem may result from incrementing or decrementing a loop counter by more than one and
then testing for equality to a specified value to terminate the loop. In this case, it is pos-
sible that the loop counter will leapfrog the specified value and execute either forever,
or until the counter wraps around and reaches its final value. This problem may also be
caused by naïve testing against limits; for example, looping while a counter is less than or
equal to
Integer.MAX_VALUE
or greater than or equal to
Integer.MIN_VALUE
.
Noncompliant Code Example
This noncompliant code example appears to iterate five times.
for (i = 1; i != 10; i += 2) {
// ...
}