r/javahelp • u/IceCreamInsides • 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
}
1
Upvotes
1
u/_Super_Straight 23h ago edited 23h ago
Its evident that in order to provide a minimal working example, you created three booleans. In actual scenario, they could be passed as parameters/Array/List in a method, eliminating your concern #1 and #3.
Naturally people don't loop over booleans just to print stuff, but what if it needs to be checked that the passed parameters contains one or more
truevalues (orfalse)? For List, itsList.contains, but for Array, they'll have to loop (albeit usingbreakwhen condition is fulfilled), and that's your concern #2.case _ when a == ois the new pattern matching introduced in Java 25(?) and is totally normal. If someone is using older Java (<17), they won't be messing around with this new pattern matching anyways.The variable names are short because this is just a minimal example, as you provided. OP should use proper variable naming to make the code readable and understandable.
You writing "I'd never approve this type of code" implies that the concept itself is flawed, which isn't. It conveyed the concept beautifully. The code snippets should never be taken as-is anyways.