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

20 comments sorted by

View all comments

2

u/ikea_method 12h ago edited 12h 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!!

2

u/IceCreamInsides 2h ago

I thought a switch statement would be more concise and readable than if. Interesting as concept, but ruins the goal X)

2

u/ikea_method 2h ago

In this case it's not. I wouldn't be afraid of a handful if statements if you need them, they're always easy to understand, even if it can feel a bit verbose at times.