Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we call a "case" inside another case in the same switch statement in Java?

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?

like image 249
Lasitha Konara Avatar asked Jul 19 '15 06:07

Lasitha Konara


People also ask

How do you call a switch case inside a switch case?

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.

Can you have multiple cases in a switch statement?

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.

Can a switch statement have two conditions Java?

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.


2 Answers

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;
    }
}
like image 152
sandalone Avatar answered Sep 30 '22 19:09

sandalone


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() { ... }
like image 24
Seelenvirtuose Avatar answered Sep 30 '22 20:09

Seelenvirtuose