My intention is to call two cases inside another case in the same switch statement,
switch (orderType) {
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case 3:
**call case 1;**
**Call case 2;**
break;
default:
break;`
}
Can we do that in Java?
Points to remember while using Switch Case There can be any number of case statements within a switch. Each case is followed by the value to be compared to and after that a colon. When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.
A Java switch statement is a multiple-branch statement that executes one statement from multiple conditions. The switch statement successively checks the value of an expression with a list of integer (int, byte, short, long), character (char) constants, String (Since Java 7), or enum types.
Although you cannot influence the switch
cases directly, you can call switch's parent method from one case and pass different arguments. For example,
void foo(int param1, String param2, ...) {
switch (param1) {
case 0:
foo(1, "some string");
break;
case 1:
//do something
break;
default:
break;
}
}
No, you can't jump to the code snippet in another switch case. You can however extract the code into an own method that can be called from another case:
switch (orderType) {
case 1:
someMethod1();
break;
case 2:
someMethod2();
break;
case 3:
someMethod1();
someMethod2();
break;
default:
break;
}
void someMethod1() { ... }
void someMethod2() { ... }
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