Volken
Volken

Reputation: 255

If statement that uses 3 boolean values

Im trying to make an if statement like this:

if(boolean1 AND boolean2 AND boolean3 == true){
   [Do this....]
}

is there a way to do an if statement in that format or will i have to do it like this:

if(boolean1 = true & boolean2 = true ect...){}

Upvotes: 0

Views: 1933

Answers (4)

Linus
Linus

Reputation: 894

There is no syntax that will work in quite in the fashion of checking three variables or statements against a single outcome. It's important to note that && and & as logical operators do not match all normal uses of the word AND (for instance, you could not check that boolean1 AND boolean2 AND boolean3 == false with && or & operators).

That said, evaluating boolean1 == true will give the same result as just boolean1. So the tedious if statement

if(boolean1 == true & boolean2 == true & boolean3 == true){...}

can be shortened to

if(boolean1 & boolean2 & boolean3){...}

It is also probably advisable to use && instead of & unless you have a specific reason to avoid short-circuiting. See Differences in boolean operators: & vs && and | vs || for more on that topic.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

Yes, but you need two &(s) for logical and (one is a bitwise and). Also, one equals is assignment (you need two, or none). Something like,

if (boolean1 && boolean2 && boolean3){
    // ...
}

Upvotes: 2

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

There is no need to compare with true (though sometimes that can be nice for readability):

if (boolean1 && boolean2 && boolean3) {...

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Least you can get is

if(boolean1 && boolean2 && boolean3 &&..){

}

Because since they are already booleans you need not to check for their value. Afaik, no other simple way.

If you have toooooooo many, create an array and write a simple util method to check if any is false

Upvotes: 3

Related Questions