0

Got this question on a quiz, but I don't understand the answer. This was on a smartphone app, so no instructor to ask about it.

 int x = 0;
switch (x) {
case 1:
    System.out.print(1);
case 0:
    System.out.print(1);
case 2:
    System.out.print(3);
}

The answer (according to quiz) is "13". I don't get it. X is initialized as "0". So when x is passed into the switch, it should go to case 0. Instructions under case 0 are to print "1". I assume this is what it is doing, but where the three? Should there be breaks in here? But, even without a break to send the flow outside of the switch, x (zero) should not fulfill the term "case 2", so printing "3" shouldn't execute. There's no default either, but that is more poor form than syntax error.

Any help appreciated. Thanks in advance, all!

Saint Razz
  • 53
  • 1
  • 7
  • 5
    There is no break, so a fall through occurs. That should be enough of a starting point for you to google. – cs95 Aug 13 '17 at 07:09
  • 1
    Do you know how to use a debugger? – user1803551 Aug 13 '17 at 07:10
  • 1
    You should create an example application and debug the code. – Jeroen Heier Aug 13 '17 at 07:11
  • First case 1 does not get entered because x is 0... Then, case 0 gets entered and prints 1 and finally, since there is no break in case 0, case 2 gets entered and executed... – deHaar Aug 13 '17 at 07:18
  • Ah. I noticed the omission of the breaks. Perhaps the question was intended to demonstrate what happens when the breaks aren't there. I was concerned that the question was answered incorrectly, since it was just an app utilizing user submitted quiz questions. – Saint Razz Aug 13 '17 at 07:34

0 Answers0