Hi all,
I am working my way through Dan's mock exam, and came across this question:
(I apologize for the formatting)
public class JMM120 {
public static void main(
String args[]) {
line 1: int i = 0, j = 0, k = 0;
line 2: label1:
line 3: for (; ; ) {
line 4: i++;
line 5: label2:
line 6: do {
line 7: k = i + j;
line 8: switch (k) {
line 9: case 0:
line 10: continue label2;
line 11: case 1:
line 12: continue label1;
line 13: case 2:
line 14: break;
line 15: case 3:
line 16: break label2;
line 17: case 4:
line 18: break label1;
line 19: default:
line 20: break label1;
line 21: }
line 22: } while (++j < 5);
line 23: }
line 24: System.out.println(i + "," + j);
line 25: }
line 26: }
It outputs: 3,1
I expected that it would be an infinate loop, but apparently my logic on break and continue statements is flawed.
Here's how I think the program runs:
line 1, line 2,
line 3 for loop starts,
line 4 i is incremented to from 0 to 1
line 5,line 6,
line 7 (k = 1 + 0, k = 1),
line 8,
line 11,
line 12 continue statment sends process back to line 2,
line 3 for loop starts again,
line 4 i is incremented to 2,
line 5, line 6,
line 7 (k = 2 + 0, k = 2),
line 8,
line 13,
line 14 break statement sends process to line 22,
line 22 j is incremented to 1, condition is true, process moves to start of while loop - line 6,
line 6,
line 7 (k = 2 + 1, k = 3),
line 8,
line 15,
line 16 breaks to label2 - line 5,
line 5,
line 6,
line 7 (k = 2 + 1, k = 3) (again),
line 8,
line 15,
line 16 breaks to label2 - line 5,
and so on...
Does the break statment when used with a label tell the process to go to the line before the label?
Does the continue statement when used with a label tell the process to go to the line after the label?
Thank you much
[ March 18, 2005: Message edited by: David Miranda ]