Reputation: 57
Logically, I would think the answer should be 0. The print out is 2.
public class Switch{
public static void main(String[] args){
int x = 3; int y = 4;
switch (x + 3) {
case 6: y = 0;
case 7: y = 1;
default: y += 1;
}
System.out.print(y);
}
}
This is how I would think the code should run:
1) add x + 3. The answer is 6.
2) case 6 correlates with answer 6. This results in 0 being the new value for 6.
3) we ignore case 7 and default because case 6 fit the needs.
4) System prints out the new value for y, which is 0.
This is where I am wrong, because 2 is printed out. Where is my thinking wrong, and what am I missing in my understanding about switch statements?
Upvotes: 1
Views: 90
Reputation: 311018
In a switch
you "fall through" the cases, starting from the one matched. So here, you enter case 6
, then case 7
and then default
. This behavior can be prevented with the break
keyword:
switch (x + 3) {
case 6:
y = 0;
break;
case 7:
y = 1;
break;
default:
y += 1;
break;
}
Upvotes: 1
Reputation: 3636
Once a Case in a Switch statement is selected, code execution is just straight down from there, which means that it´s executing all of the cases. If you don´t want that, use Break statements:
switch (x + 3) {
case 6: y = 0; break;
case 7: y = 1; break;
default: y += 1; break;
}
Upvotes: 3