Using the equals operator ==
with Boolean datatypes works the same way, but it can sometimes be misleading.
Boolean isSunny = true; Boolean isWarm = true; Boolean isSunnyAndWarm = isSunny == isWarm; // isSunnyAndWarm is TRUE because true is equal to true. //Then, with different values isSunny = false; isWarm = true; isSunnyAndWarm = isSunny == isWarm; // isSunnyAndWarm is FALSE because false is NOT equal to true.
We can compare boolean variables to true
and false
literals like this:
Boolean isCloudy = true; Boolean result = isCloudy == true; // This is true result = isCloudy == false; // result is now FALSE because true is not equal to false.
So far, that's pretty straightforward, but we could face trouble when comparing two false
statements. Take the first example we looked at but flip the variable assignments so that it's neither sunny nor warm:
Boolean isSunny = false; Boolean isWarm = false;
In this setup, we'd expect isSunnyAndWarm
to be false
, but the code will do something else:
Boolean isSunny = false; Boolean isWarm = false; Boolean isSunnyAndWarm = isSunny == isWarm; // isSunnyAndWarm is TRUE, because false is equal to false.
Yikes! That's different from what we expected. Since both sides of the ==
operator are the same, the statement evaluates to true
even though both statements are false. Stick around for the Conditions Course, where we'll learn more robust ways to compare Booleans.