Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Can I fall through only one case in a switch statement

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
}
like image 358
stephenwade Avatar asked Mar 25 '13 02:03

stephenwade


People also ask

How many cases can a switch statement have in Java?

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...

Can you have multiple cases in a switch statement?

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.

Do Java switch statements fall through?

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.

What are the rules for switch statement?

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.


1 Answers

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.

like image 184
nicholas.hauschild Avatar answered Sep 28 '22 06:09

nicholas.hauschild