I do not see any error here, at least not how the language works. The design behavior of the switch is that it starts executing statements on the case label that matches the argument, and then continues to the end of the block. So
switch (x) { case 1: // do thing 1 case 2: // do thing 2 case 3: // do thing 3 default: // do nothing }
will do both things 2 and 3 if x is 2, and will do things 1, 2 and 3 if x is 1.
To get the behavior you're probably looking for, run each case with break :
switch (x) { case 1: // do thing 1 break; case 2: // do thing 2 break; case 3: // do thing 3 break; default: // do nothing break; }
(strictly speaking, break at the very end is not necessary, but I often put it out of habit).
The reason you didnβt have this problem in the first code example is because return looks like a super- break : it has the same effect as break , namely, completing execution in the switch block, but also completing everything method.
source share