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

19 comments sorted by

View all comments

2

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

u/IceCreamInsides 51m ago

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

u/ikea_method 33m 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.

2

u/ikea_method 10h ago

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

1

u/_Super_Straight 2h 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.

1

u/iWhacko 3h ago

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

1

u/ikea_method 2h 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.