Can we call a β€œcase” inside another case in the same switch statement in Java?

My intention is to call two cases in 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 this in Java?

+6
source share
4 answers

Although you cannot directly influence switch cases, you can call the parent switch method from the same case and pass different arguments. For instance,

 void foo(int param1, String param2, ...) { switch (param1) { case 0: foo(1, "some string"); break; case 1: //do something break; default: break; } } 
+5
source

No, you cannot go to the code snippet in another switch case. However, you can extract the code into your own method, which 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() { ... } 
+5
source

You cannot just call another case block like this. However, you could 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; } } 
+1
source

As others have pointed out, you can implement your switching cases inside a method that takes a parameter that matches the desired switch case. These switching cases can recursively call the same method with the required switching cases. Here is a complete working example that allows you to check if a year is a leap year or not:

 public class LeapYear { static int year = 2016; public static void main(String[] args) { leapSwitch(1); } public static void leapSwitch(int switchcase) { switch (switchcase) { case 1: { if (year % 4 == 0) { leapSwitch(2); } else { leapSwitch(5); } } break; case 2: { if (year % 100 == 0) { leapSwitch(3); } else { leapSwitch(4); } } break; case 3: { if (year % 400 == 0) { leapSwitch(4); } else { leapSwitch(5); } } break; case 4: { System.out.println(year+ " is a leap year!"); } break; case 5: { System.out.println("Not a leap year..."); } break; } } } 
0
source

All Articles