Java Reference
In-Depth Information
The previous nested for loop is obviously a contrived example, but it
is the type of example you will find on the exam. My advice is to write
down the values of each variable through each iteration of the loop. Take
your time and step through the loops carefully.
Here is a breakdown of each iteration through the loop:
1. a equals 1 the first time through the outer loop, and x equals 'a' the first time
through the inner loop, so '1a' is output on line 14. Then x equals 'b' , so the con-
tinue executes and control jumps to the x++ update statement on line 11. x equals 'c'
and '1c' displays.
2. a equals 2 the second time through the outer loop. The inner loop executes three times,
but line 12 is true on each iteration so the continue executes each time and the print
statement is skipped. No output occurs when a equals 2 .
3. a equals 3 on the next iteration, which is similar to the case when a was 1 .
The continue executes when x is 'b' , so the output is '3a' and '3c' .
4. Similarly, when a equals 4 the output is '4a' and '4c' .
Therefore, the output of the code is
1a 1c 3a 3c 4a 4c
As with break statements, a continue statement can declare a label denoting the loop
to continue on. The following nested loops demonstrate a labeled continue statement.
Examine the code and see if you can determine its output:
19. char row = 'A';
20. rowlabel : while(row <= 'D') {
21. System.out.print(row++);
22. for(int i = 1; i <= 5; i++) {
23. if(i%2 == 0)
24. continue;
25. if(i%3 == 0) {
26. System.out.println();
27. continue rowlabel;
28. }
29. System.out.print(i);
30. }
31. }
Search WWH ::




Custom Search