Java Reference
In-Depth Information
do
-
while
Loops
The
do
loop is just like a
while
loop with one major difference—the place in the loop
when the condition is tested.
A
while
loop tests the condition before looping, so if the condition is
false
the first
time it is tested, the body of the loop never executes.
A
do
loop executes the body of the loop at least once before testing the condition, so if
the condition is
false
the first time it is tested, the body of the loop already will have
executed once.
The following example uses a
do
loop to keep doubling the value of a
long
integer until
it is larger than 3 trillion:
long i = 1;
do {
i *= 2;
System.out.print(i + “ “);
} while (i < 3000000000000L);
The body of the loop is executed once before the test condition,
i <
3000000000000L,
is evaluated; then, if the test evaluates as
true
, the loop runs again. If it is
false
, the
loop exits. Keep in mind that the body of the loop executes at least once with
do
loops.
4
In all the loops, the loop ends when a tested condition is met. There might be times when
something occurs during execution of a loop and you want to exit the loop early. In that
case, you can use the
break
and
continue
keywords.
You already have seen
break
as part of the
switch
statement;
break
stops execution of
the
switch
statement, and the program continues. The
break
keyword, when used with a
loop, does the same thing—it immediately halts execution of the current loop. If you
have nested loops within loops, execution picks up with the next outer loop. Otherwise,
the program simply continues executing the next statement after the loop.
For example, recall the
while
loop that copied elements from an integer array into an
array of floating-point numbers until either the end of the array or a
1
was reached. You
can test for the latter case inside the body of the
while
loop and then use
break
to exit
the loop:
int count = 0;
while (count < array1.length) {
if (array1[count] == 1)
break;
array2[count] = (float) array2[count++];
}