Here is a small confusion so kindly pardon my ignorance. Here is a code snippet.
public class SwitchTest {
public static void main(String[] args) {
int x = 2;
switch (x) {
case 1:
System.out.println("1");
break;
default:
System.out.println("helllo");
case 2:
System.out.println("Benjamin");
break;
}
}
}
Here, if value of x is 2, only Benjamin
is printed. That's perfectly fine. Now lets suppose, i change value of x to 3
, not matching any case, than its a fall through from default case
. Ain't compiler needs to match every case for 3, by that time CASE 2
will be passed, than why it goes back to default and prints hello Benjamin. Can someone explain please?
Thanks,
You need to add a break;
statement to break out of the switch
block.
switch (x) {
case 1:
System.out.println("1");
break;
default:
System.out.println("helllo");
break; // <-- add this here
case 2:
System.out.println("Benjamin");
break;
}
Generally speaking, it is also better coding practice to have your default:
case be the last case in the switch
block.
In this case, the switch is following the pattern:
x==1? No, check next case
default? Not done yet, check other cases
x==2? No, check next case
//No more cases, so go back to default
default? Yes, do default logic
// no break statement in default, so it falls through to case 2: logic without checking the case
output case 2 logic
break
Notice how the block will jump over the default case, and save it until a later time unless we have exhausted all other possible cases.