user10111962
user10111962

Reputation:

Is it possible to exit (return) from a switch case from a method in the same case.?

Is it possible to exit (return) from a switch case from a method in the same case?

Given this code:

switch(int blaah) {
    case 1: 
        some code here;
        break;
    case 2: 
        myMethod();
        some code here;
        break;
    default:
        some code here;
}

public void myMethod() {

    if(boolean condition) {
        return;  
        /*I want this return valuates in switch case too.
        so the switch case exit without executing the rest of code of "case 2" */

    }
        some code here;
}

I know the return here just skip the rest of the codes in myMethod. I am looking for something that tells the switch case to stop execution from the method.

Upvotes: 0

Views: 66

Answers (2)

Khemraj Sharma
Khemraj Sharma

Reputation: 58934

Best option would be

   case 2: 
        if (someCondition) {
            myMethod();
        }
         else {
          // some code
          }
        break;

Upvotes: 0

Thiyagu
Thiyagu

Reputation: 17880

It is difficult to give a meaningful solution without the full context.

However...

You can return a boolean result from the method and based on it the switch case can decide to continue or not.

public boolean myMethod() {

    if(boolean condition) {
        return false;
    }
     //some code here;
     return true;
}


switch(int blaah) {
    case 1: 
        some code here;
        break;
    case 2: 
        if (myMethod()) {
            //some code here; //Execute only if the method signalled to do so
        }
        break;
    default:
        some code here;
}

Another option:

If if(boolean condition) is the first thing you do in the method, you can evaluate it in the switch case itself and can avoid calling the method if it turned out to be true and break immediately.

case 2: 
        if (boolean condition) {
            myMethod();
            //some code here;
        }
        break;

Upvotes: 2

Related Questions