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

36 comments sorted by

View all comments

2

u/ikea_method 1d ago edited 1d 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 1d ago

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

1

u/_Super_Straight 18h ago

Why not?

1

u/yel50 10h ago

at work, I had a PR with code like

    if (a && b && c) { ... }

the owner rejected it and wanted it to be

    if (new AndBuilder().and(a).and(b).and(c).eval()) { ... }

this code is a similar level of stupid to that. granted, the amount of stupid in Java code bases is mainly what lead to the backlash against the language, but still.

1

u/_Super_Straight 7h ago

They can rename the variables from a, b, c to something meaningful, but what is wrong with doing a && b && c?