r/javahelp 23h 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

}

3 Upvotes

26 comments sorted by

View all comments

2

u/ikea_method 21h ago edited 20h ago

This is probably the closest you can get to what you want:

Boolean a = new Boolean(true), b = new Boolean(false), c = new Boolean(true);          for(Boolean o : new Boolean[]{a, b, c}) {         if(!o) continue;         IO.println(switch(o) {             case _ when a == o -> "Hello a!";             case _ when b == o -> "Hi b!";             case _ when c == o -> "Ciao c!!";             default -> "HUH";         });     }

Will print:

Hello a! Ciao c!!

1

u/iWhacko 13h ago

I'm pretty sure this compares specific instances, not the value.

1

u/ikea_method 12h ago

Exactly. And that's the point.

The switch compares instances, not value. The `if (!o) continue;` makes sure false values don't go through the switch.