In Java, can I fall through only one of the cases in a switch
statement? I understand that if I break
, I will fall through to the end of the switch
statement.
Here's what I mean. Given the following code, on case 2, I want to execute case 2 and case 1. On case 3, I want to execute case 3 and case 1, but not case 2.
switch(option) {
case 3: // code
// skip the next case, not break
case 2: // code
case 1: // code
}
You can use it as many as you like, but it is not a good thing, as your code will become long and boring, this can be avoided by using loops, functions, or several other methods. You can write as many as you want...
Control passes to the case statement whose constant-expression value matches the value of expression . The switch statement can include any number of case instances. However, no two constant-expression values within the same switch statement can have the same value.
Following rules govern the fall through the behavior of switch statement. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
Rules for switch statement in C language 1) The switch expression must be of an integer or character type. 2) The case value must be an integer or character constant. 3) The case value can be used only inside the switch statement. 4) The break statement in switch case is not must.
No, what you are after is not possible with a switch
statement. You will fall through each case
until you hit a break
. Perhaps you want case 1
to be outside of your switch
statement, so that it is executed regardless.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With