Can we call a "case" inside another case in the same switch statement in Java?
You can't just call a another case
block like this. What you could do, though, is wrap each of these blocks in a method, and reuse them:
private void doSomething() {
// implementation
}
private void doSomethingElse() {
// implementation
}
private void runSwitch(int order) {
switch (orderType) {
case 1:
doSomething();
break;
case 2:
doSomethingElse();
break;
case 3:
doSomething();
doSomethingElse();
break;
default:
break;
}
}
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() { ... }