Java Reference
In-Depth Information
The for loop is well suited to situations requiring definite iteration. For instance, it is common
to use a for loop when we wish to do something to every element in an array, such as printing
out the contents of each element. This fits the criteria, as the fixed number of times corresponds
to the length of the array and the variable is needed to provide an incrementing index into the
array.
A for loop has the following general form:
for ( initialization; condition; post-body action ) {
statements to be repeated
}
The following concrete example is taken from the printHourlyCounts method of the
LogAnalyzer :
for(int hour = 0; hour < hourCounts.length; hour++) {
System.out.println(hour + ": " + hourCounts[hour]);
}
The result of this will be that the value of each element in the array is printed, preceded by its
corresponding hour number. For instance:
0: 149
1: 149
2: 148
...
23: 166
When we compare this for loop to the for-each loop, we notice that the syntactic difference is in
the section between the parentheses in the loop header. In this for loop, the parentheses contain
three separate sections, separated by semicolons.
From a programming-language design point of view, it would have been nicer to use two dif-
ferent keywords for these two loops, maybe for and foreach . The reason that for is used
for both of them is, again, a historical accident. Older versions of the Java language did not
contain the for-each loop, and when it was finally introduced, Java designers did not want
to introduce a new keyword at this stage, because this could cause problems with existing
programs. So they decided to use the same keyword for both loops. This makes it slightly
harder for us to distinguish these loops, but we will get used to recognizing the different
header structures.
Even though the for loop is often used for definite iteration, the fact that it is controlled by a
general boolean expression means that it is actually closer to the while loop than to the for-
each loop. We can illustrate the way that a for loop executes by rewriting its general form as an
equivalent while loop:
initialization;
while( condition ) {
statements to be repeated
post-body action
}
 
Search WWH ::




Custom Search