Java Reference
In-Depth Information
< Day Day Up >
Puzzle 34: Down for the Count
Like the programs in
Puzzles 26
and
27
, this program has a single loop, keeps track of the number
of iterations, and prints that number when the loop terminates. What does the program print?
public class Count {
public static void main(String[] args) {
final int START = 2000000000;
int count = 0;
for (float f = START; f < START + 50; f++)
count++;
System.out.println(count);
}
}
Solution 34: Down for the Count
A superficial analysis might suggest that this program would print
50
. After all, the loop variable (
f
)
is initialized to 2,000,000,000, the final value is 50 more than the initial value, and the loop has the
traditional "half-open" form: It uses the
<
operator, which causes it to include the initial value but
not the final value.
This analysis, however, misses a key point: The loop variable is a
float
rather than the traditional
int
. Remember back to
Puzzle 28
; it is apparent that the increment (
f++
) will not work. The initial
value of
f
is close to
Integer.MAX_VALUE
, so it requires 31 bits to express precisely, and the
float
type provides only 24 bits of precision. Incrementing such a large
float
value will not change it.
Therefore, it would appear that this program should loop indefinitely, with
f
never getting any
closer to its terminal value. If, however, you ran the program, you found that it doesn't loop
indefinitely; in fact, it terminates immediately, printing
0
. What gives?
The problem is that the termination test fails in much the same way that the increment does. The
loop runs only so long as the loop index
f
is less than
(float)(START + 50)
. The promotion from
int
to
float
is performed automatically when comparing an
int
to a
float
[JLS 15.20.1].
Unfortunately, this promotion is one of the three widening primitive conversions that can result in
Search WWH ::
Custom Search