Java Reference
In-Depth Information
Here is the sequence of events for this
while
loop:
1.
count
is 1 and
sum
is 0, so the first time through the loop
sum
is 0 + 1 = 1 and
count
gets incremented to 2.
2.
Line 8 is
false
, the body of the loop is complete, and control jumps back up to the
boolean
expression on line 6.
3.
The loop executes again,
sum
is now 1 + 2 = 3, and
count
is now 3, so the loop executes
again.
4.
sum
is 3 + 3 = 6,
count
is 4, and the loop executes again.
5.
sum
is 6 + 4 = 10,
count
is 5, and the loop executes again.
6.
sum
is 10 + 5 = 15,
count
is 6, and line 8 is finally
true
.
7.
Line 9 executes, causing
myloop
to terminate and control jumps to line 12.
Therefore, the output of this code is
sum = 15
count = 6
Using Labels
Note that the
myloop
label is not required in the previous example, but you can still use
a label even when it is unnecessary. You might use a label for clarifi cation if a loop is
long and it is unclear what is being affected by a
break
statement. You might also use
a label to ensure that modifi cations to the code later do not affect your use of the
break
statement.
There are also situations where a label is required, as we will see in the next example.
The
myloop
label is not needed in the previous example, but there are situations where a
label is necessary (especially in nested loops) to obtain the desired behavior of a break. To
demonstrate this type of situation, let's start with a nested loop that does not use labels. See
if you can determine the behavior of the following loops:
15. int x = 1;
16. while(x <= 10) {
17. System.out.print(x++ + “ “);
18. for(int y = 10; y >= 1; y--) {
19. System.out.print(y + “ “);
20. if(y == 8)
21. break;
22. }
23. }
Search WWH ::
Custom Search