Java OCA OCP Practice Question 232

Question

Given:

3. public class Main {
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++;/*from   w ww .  j a va 2  s  .  c o  m*/
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. }

What is the result?

  • A. 9 10 d
  • B. 8 9 10 d
  • C. 9 10 10 d
  • D. 9 10 10 d 13
  • E. 8 9 10 10 d 13
  • F. 8 9 10 9 10 10 d 13
  • G. Compilation fails


D is correct.

Note

Did you catch the static initializer block?

Switches work on "fall-through" logic.

Fall-through logic applies to the default case, which is used when no other case matches.




PreviousNext

Related