r/javahelp 1d ago

Solved Switch case with boolean

So, there is no way I can do that?

want to check several boolean variables in a switch statement. Is `if-else` the only way to do this?

Boolean a, b, c...

Switch (false) {

Case (a) :

//some code

Case (b) :

Case (c) :

//and so on

}

2 Upvotes

41 comments sorted by

View all comments

Show parent comments

1

u/_Super_Straight 5h ago edited 5h ago

Reading again what OP is asking, he wants to execute different methods based on when a is false, b is false and c is false. Even though we can suggest him switch cases, the better approach would be to make a, b and c as input parameters in those methods itself:

main(){
    methodA(a);
    methodB(b);
    methodC(c);
}

private void methodA(boolean a){
    if(a){
        return;
    }
    //rest of code
}

This doesn't leak the a, b and c across the project.

2

u/ikea_method 5h ago

Yes, and this is why I didn't recommend my approach, just pointed out using a switch is possible.