Java Reference
In-Depth Information
So the alternative form for the body of printHourlyCounts would be
int hour = 0;
while(hour < hourCounts.length) {
System.out.println(hour + ": " + hourCounts[hour]);
hour++;
}
From this rewritten version, we can see that the post-body action is not actually executed until
after the statements in the loop's body, despite the action's position in the for loop's header. In
addition, we can see that the initialization part is executed only once—immediately before the
condition is tested for the first time.
In both versions, note in particular the condition
hour < hourCounts.length
This illustrates two important points:
All arrays contain a field length that contains the value of the fixed size of that array. The
value of this field will always match the value of the integer expression used to create the ar-
ray object. So the value of length here will be 24.
The condition uses the less-than operator, <, to check the value of hour against the length of the
array. So in this case the loop will continue as long as hour is less than 24. In general, when we
wish to access every element in an array, a for-loop header will have the following general form:
for(int index = 0; index < array .length; index++)
This is correct, because we do not wish to use an index value that is equal to the array's
length; such an element will never exist.
4.16.7
Arrays and the for-each loop
Could we also rewrite the for loop shown above with a for-each loop? The answer is: almost.
Here is an attempt:
for(int value : hourCounts) {
System.out.println(": " + value);
}
This code will compile and execute. (Try it out!) From this fragment, we can see that arrays
can, in fact, be used in for-each loops just like other collections. We have, however, one prob-
lem: we cannot easily print out the hour in front of the colon. This code fragment simply omits
printing the hour, and just prints the colon and the value. This is because the for-each loop does
not provide access to a loop-counter variable, which we need in this case for printing the hour.
To fix this, we would need to define our own counter variable (similar to what we did in the while
loop example). Instead of doing this, we prefer using the old-style for loop because it is more
concise.
 
Search WWH ::




Custom Search