Java Reference
In-Depth Information
The Enhanced for Loop
Relatively recently, a new form of the for loop, called the enhanced for , was added to Java.
The enhanced for provides a streamlined way to cycle through the contents of a collection
of objects, such as an array. The enhanced for loop is discussed in Chapter 5 , after arrays
have been introduced.
The while Loop
Another of Java's loops is the while . The general form of the while loop is
while (condition) statement ;
where statement may be a single statement or a block of statements, and condition defines
the condition that controls the loop. The condition may be any valid Boolean expression.
The loop repeats while the condition is true. When the condition becomes false, program
control passes to the line immediately following the loop.
Here is a simple example in which a while is used to print the alphabet:
Here, ch is initialized to the letter a. Each time through the loop, ch is output and then in-
cremented. This process continues until ch is greater than z.
As with the for loop, the while checks the conditional expression at the top of the loop,
which means that the loop code may not execute at all. This eliminates the need for per-
forming a separate test before the loop. The following program illustrates this characteristic
of the while loop. It computes the integer powers of 2, from 0 to 9.
Search WWH ::




Custom Search