This is what happens here: On z=0: The value of z matches with the 4th case label since x-2=0. Thus, 2 is printed . As there are no more statements after this case label, the loop gets re-iterated.
On z=1 The value of z matches with the 2nd case label since x-1=1. Thus 1 is printed. As break is encountered, everything else in the switch block is skipped and the loop is re-iterated.
On z=2 The value of z matches with the 1st case label since x=2. Thus 0 is printed. As there is no break statement the next case label also gets executed and 1 is printed. On encountering break after the print statement, the loop is re-iterated.
On z=3 The value of z does not match with any of the case label thus the default label is executed which prints 'def'. Again, due to absence of break statement the next case is also executed which prints 2. As this is the last statement, the loop is re-iterated.
Thus the output is: 2101def2
Hope it helps.
SCJP 1.4<br />SCWCD 1.4
Joined: Jul 04, 2005
Thanks a lot its very clear now. sometimes its very frustrating if your stuck on some basics and trying to solve.
I would post selected questions from what mocks i am solving hope this will help others to revise.