Java Reference
In-Depth Information
The final statement in the body of the while loop illustrates a special operator for incrementing
a numerical variable by 1:
index++;
This is equivalent to
index = index + 1;
So far, the for-each loop is clearly nicer for our purpose. It was less trouble to write, and it is safer.
The reason it is safer is that it is always guaranteed to come to an end. In our while-loop version,
it is possible to make a mistake that results in an infinite loop. If we were to forget to increment
the index variable (the last line in the loop body), the loop condition would never become false ,
and the loop would iterate indefinitely. This is a typical programming error that catches out even
experienced programmers from time to time. The program will then run forever. If the loop in
such a situation does not contain an output statement, the program will appear to “hang”: it seems
to do nothing, and does not respond to any mouse clicks or key presses. In reality, the program
does a lot. It executes the loop over and over, but we cannot see any effect of this, and the program
seems to have died. In BlueJ, this can often be detected by the fact that the red-and-white-striped
“running” indicator remains on while the program appears to be doing nothing.
So what are the benefits of a while loop over a for-each loop? They are twofold: first, the while
loop does not need to be related to a collection (we can loop on any condition that we can write
as a boolean expression); second, even if we are using the loop to process the collection, we do
not need to process every element—instead, we could stop earlier if we wanted to by includ-
ing another component in the loop's condition that expresses why we would want to stop. Of
course, strictly speaking, the loop's condition actually expresses whether we want to continue,
and it is the negation of this that causes the loop to stop.
A benefit of having an explicit index variable is that we can use its value both inside and outside
the loop, which was not available to us in the for-each examples. So we can include the index in the
listing if we wish. That will make it easier to choose a track by its position in the list. For instance:
int index = 0;
while(index < files.size()) {
String filename = files.get(index);
// Prefix the file name with the track's index.
System.out.println(index + ": " + filename);
index++;
}
Having a local index variable can be particularly important when searching a list, because it
can provide a record of where the item was located, which is still available once the loop has
finished. We shall see this in the next section.
4.10.3
Searching a collection
Searching is one of the most important forms of iteration you will encounter. It is vital, there-
fore, to have a good grasp of its essential elements. The sort of loop structures that result occur
again and again in practical programming situations.
 
Search WWH ::




Custom Search