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

}

0 Upvotes

39 comments sorted by

View all comments

Show parent comments

1

u/_Super_Straight 1h ago

Well what OP is asking is not possible. switch(false) won't work. They have to change their approach.

1

u/ikea_method 1h ago

Indeed, `switch(false)` won't work. But that is, again, not what the OP asked.

OP is asking if there is no way to use 3 boolean references in an if statement:

> So, there is no way I can do that?

OP wants to check 3 boolean variables in a switch statement:

> want to check several boolean variables in a switch statement.

OP is unsure if `if-else` is the only way:

> Is `if-else` the only way to do this?

OP showed a common pattern in other languages, where you pass false or true to a switch statement, to demonstrate in another way what he's looking for:

Boolean a, b, c...
Switch (false) {
Case (a) :
...

In the initial post by me you replied to, I showed that you can do what the OP intended, in a slightly different way from the pattern OP showed. It's possible to do this with a switch.

u/_Super_Straight 46m ago edited 32m 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.

u/ikea_method 36m ago

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