Java Reference
In-Depth Information
7.
When the program reaches the end of the loop, it will return to the conditional expression to see if
it will enter the loop again. Since 2 is still less than 10, it will loop again.
8.
The variable
doubled
is 2*2 or 4 in this iteration of the loop.
9.
Another line will be output to the console, this time reading:
2 times two equals 4
.
10.
The integer
i
will be reassigned the value of
i
+1
or
i
=3
.
11.
This will continue until
i
=11
and then the conditional expression will evaluate to
false
. The
while
loop will be skipped on this last iteration and the program will continue below the loop.
12.
One final line will be output to the console indicating the end of the program.
13.
If you executed the
for
loops in the other Try It Out exercises in this chapter, you'll notice that
they all produce the same output. For these simple examples, the loops can be used somewhat
interchangeably, with some small adaptations. You will encounter situations in the later chapters
that are more suited to one type of loop over others.
What Is a do while Loop?
There is also an alternate form of a
while
loop that's useful in some circumstances. It is called a
do
while
loop and is very similar to the
while
loop. As you'll recall, a
while
loop starts by evaluating
a conditional statement, much like a
for
loop begins by checking the termination condition. A
do
while
loop is different because it will first execute (“do”) the statements within the loop and then
check the conditional expression (“while”) to see if it should repeat the loop. A standard
do while
loop uses the following syntax:
do {
/*execute these statements*/
} while (/*conditional expression*/);
To demonstrate the difference, consider the small example from the previous section of a
while
loop.
int i = 10;
while (i > 0){
System.out.println(i);
i = i - 1;
}
Now the same example is presented as a
do while
loop.
int i = 10;
do {
System.out.println(i);
i = i - 1;
} while (i > 0);
Search WWH ::
Custom Search