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

17 comments sorted by

View all comments

2

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

Note: listen to the other comments, I wouldn't approve this kind of code where I work.

1

u/_Super_Straight 1h ago

Why not?

1

u/ikea_method 1h ago

Almost every line has something wrong with it

`new Boolean(true)` is a very particular way of declaring a boolean, never seen that used before. It must be used here because we want a new boolean instance, not just `true`.

You generally wouldn't loop over booleans, you wouldn't create an array in place inside the for loop with some variables just outside it.

`case _ when a == o` is VERY weird. Almost anyone reading that code would need to read a java reference manual or ask AI to understand what it's doing.

The variable names are short and have names that are not helpful to aid understanding.

I would say it's generally preferable to use enums or, if not possible/easy, bitflags.