Why does this,
public class Bar
{
public static void main(String[] args)
{
int i = 1;
switch(i)
{
case 0:
case 1:
case 2:
System.out.println("Case 2 being executed");
break;
default:
break;
}
}
}
output this,
Case 2 being executed
?
How is it even possible to enter the case block for an input value of 2 when the input value is explicitly 1? Note that I’m aware I can avoid this behavior by adding a break statement in the case block for 1.
This behaviour is called fall-through which is quite common mistake with beginners working with
switch-case. Actually,case 1:does execute first. But, since there is nobreakstatement in case 1, yourswitch-casegoes onto executing the next cases, until it finds abreakstatement. So, it will even execute the code forcase 2:and hence the output. And then it breaks after executingcase 2, as it encounters a break.So, change your
swich-caseto: –to see the intended behaviour.