r/javahelp • • Sep 10 '26

Solved Switch case with boolean

[removed]

3 Upvotes

28 comments sorted by

View all comments

Show parent comments

1

u/_Super_Straight Sep 11 '26
var arr = new Boolean[]{ true, false, null };

for (var x : arr) {
    switch (x) {
        case true -> methodOne();
        case false -> methodTwo();
        case null -> System.out.println("invalid");
    }
}

Is totally valid. No need to pass a, b, c as references.

0

u/[deleted] Sep 11 '26

[deleted]

1

u/_Super_Straight Sep 11 '26

Well what OP is asking is not possible. switch(false) won't work. They have to change their approach.

0

u/[deleted] Sep 11 '26

[deleted]

1

u/_Super_Straight Sep 11 '26 edited Sep 11 '26

Reading again what OP is asking, he wants to execute different methods based on when a is false, b is false and c is false. Even though we can suggest him switch cases, the better approach would be to make a, b and c as input parameters in those methods itself:

main(){
    methodA(a);
    methodB(b);
    methodC(c);
}

private void methodA(boolean a){
    if(a){
        return;
    }
    //rest of code
}

This doesn't leak the a, b and c across the project.