Java Reference
In-Depth Information
Study the following while loop. How many times will it execute? How will
the output look?
int x = 1;
while(x <= 10)
{
System.out.println(x);
x++;
}
Notice that x starts at 1 and is incremented by 1 each time through the loop;
therefore, the println(x) statement executes 10 times, and the output is:
1
2
3
4
5
6
7
8
9
10
Note that when the loop is done executing, the value of x will be 11. In this
example, the variable x is referred to as the loop counter because x changes each
time through the loop, and it is the value of x that determines when the loop
will terminate.
It is possible to write a while loop that never executes. If the Boolean expres-
sion is initially false, the statements in the loop are not executed. For example:
int i = -10;
while(i > 0)
{
System.out.println(“You will not see this.”);
}
Similarly, it is possible to write an infinite while loop that never terminates.
For example:
int i = 1;
while(i > 0)
{
System.out.println(i++);
}
Search WWH ::




Custom Search