You are on page 1of 4

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, and it 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's a simple example in which a while is used to print the alphabet. In this program, ch
is initialized to the letter a. Each time through the loop, ch is output and then
incremented. 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
performing 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. Notice that the while loop executes only when e is
greater than 0. Thus, when e is zero, as it is in the first iteration of the for loop, the while
loop is skipped.
This is the output from the program:
Summary

In this lesson, you learned that 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.

You also learned that the condition may be any valid Boolean expression. As long as the
condition is true the loop will repeat. Program control will pass to the code immediately
following the loop when the condition becomes false.

You might also like