Thursday, August 5, 2010

Switch: Ebb.java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 5, Question 8




This question seems to trick many people notice
a. the static initialization block at the end of Ebb class
b. only one of the case statements in the switch block has a break statement

Let's trace this code:

Before we enter the for loop on line 5, the value of x is assigned 7, then incremented to 8.

We enter the loop and int y=0. Once execution enters the loop, x is incremented again to 9.
case (9) appends the value "9 " to String s. Since there is no break statement to exit the switch block, program "fall-thru" to the next line.
case(10) executes and appends the value of "10 " to s, and then breaks from the switch block.

y=1, for loop on line 5 continues and now x is incremented to 10.
case(10) executes and appends the value of "10 " to s, and then breaks from the switch block.

y=2, for loop on line 5 continues and now x is incremented to 11.
default executes and appends the value of "d " to s. Since there is no break statement to exit the switch block, program "fall-thru" to the next line.
case(13) executes and appends the value of of "13 " to s

y=3, but for loop to execute, condition y<3 must be true

Execution of program is complete and output is

9 10 10 d 13

No comments:

Post a Comment