Hello,

I am studying for SCJP 6 Exam, and came across this question which shows code as asks for the output

3. public class Ebb {
 4.   static int x = 7;
 5.   public static void main(String[] args) {
 6.     String s = "";
 7.     for(int y = 0; y < 3; y++) {
 8.       x++;
 9.       switch(x) {
10.         case 8: s += "8 ";
11.         case 9: s += "9 ";
12.         case 10: { s+= "10 "; break; }
13.         default: s += "d ";
14.         case 13: s+= "13 ";
15.       }
16.     }
17.     System.out.println(s);
18.   }
19.   static { x++; }
20. }

The answer says 9 10 10 d 13 will be output. However, when I hand-traced the program, I keep getting 9 10 d 13. Can you please help? Below is my trace:

step 1: x is set to 7

step 2: x is incremented to 8 (because of static x++)

step 3: string s is initialized to ""

step 4: for loop begins, y is set to 0

step 5: x is incremented to 9

step 6: case 9 appends 9 to string s

step 7: for loop, y is set to 1

step 8: x is incremented to 10

step 9: case 10 appends 10 to string s and breaks out of switch, y is set to 2

step 10: x is incremented to 11

step 11: case default appends d to string s

step 12: case 13 appends 13 to string s, y is set to 3

step 13: loop exits, and prints 9 10 d 13

Recommended Answers

All 4 Replies

Your "Step 6" will do a little more than what you noted. See if you can spot it.

Hello,

I am studying for SCJP 6 Exam, and came across this question which shows code as asks for the output

9.       switch(x) {
10.         case 8: s += "8 ";
11.         case 9: s += "9 ";
12.         case 10: { s+= "10 "; break; }
13.         default: s += "d ";
14.         case 13: s+= "13 ";
15.       }

step 6: case 9 appends 9 to string s

step 7: for loop, y is set to 1

Read up on how a switch statement works. Step 6 and 7 is your trouble spot.

In step 6 (case 9: ), s takes on the value of "9 ". The program then continues on and executes the code in the (case 10: ) portion of the switch statement.

Look very close at the switch statement usage on
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/switch.html

Yes, I was trying to steer him towards figuring that out for himself... :icon_rolleyes:

commented: haha. shafted. +4

Now it seems so obvious even though I was staring at it for three days. At case 9, it will drop to case 10, print 10, then break from the switch. Finally it will go back to the for loop where x gets incremented to 10. Wow, I got a LOT of studying to do :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.