Reputation: 44240
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.
Upvotes: 0
Views: 928
Reputation: 213193
How is it even possible to enter the case block for an input value of 2 when the input value is explicitly 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 no break
statement in case 1, your switch-case
goes onto executing the next cases, until it finds a break
statement. So, it will even execute the code for case 2:
and hence the output. And then it breaks after executing case 2
, as it encounters a break.
So, change your swich-case
to: -
switch(i)
{
case 0: break;
case 1: break;
case 2:
System.out.println("Case 2 being executed");
break;
default:
break;
}
to see the intended behaviour.
Upvotes: 9
Reputation: 3941
The switch statement will run through all case blocks until it reaches the first break or the end of the switch statement.
So, in your case it executes all blocks until it reaches the break in the second block.
If there were any statements in the "0" and the "1" block, these would also be executed.
This behaviour can also be really useful.
Upvotes: 1
Reputation: 2685
Because you didn't put a break after case 1 so it uses case 2's logic. You need a break statement after every case or the compiler will just go down to the next line.
Upvotes: 1