Boolean Expressions

index
BASIC

A boolean expression is an expression that results in a boolean value, that is, in a value of either true or false.

More complex boolean expressions can be built out of simpler expressions, using the following boolean operators:

Operator Name of operator What it means Example
&& and True if and only if both sides are true wet && cold
|| or True if either side is true (or if both are true) rich || famous
! not Changes true to false, and false to true !happy
^ exclusive or True if either side is true (but not both) walking ^ ridingBus

Parentheses can be used for grouping the parts of complex boolean expressions. For example:

if ((wet && cold) || (poor && hungry)) {
    System.out.println("I'm miserable!");
} 

The println statement will be executed if wet and cold are both true, or if poor and hungry are both true.

There are six arithmetic tests that can be used to create boolean values:

Operator Name of operator
< less than
<= less than or equal to
== equal to
!= not equal to
>= greater than or equal to
> greater than

These have the obvious meanings, and can be combined with the boolean operators. For example:

if (score < 0 || score > 100) {
    System.out.println("Score has an illegal value.");
} 

Boolean expressions are most often used as conditions (as in the examples above). However, they may be used other places as well, for example:

comfortable = warm && dry;

System.out.println(x >= 0 && x <= 100);

printResults(data, verbose);

When an expression contains two or more operators, the order in which operations are done is defined by parentheses and by the precedence of the operators. Thus, for example, the following two expressions are equivalent.

x > 1 && x < 100 || x == 300 
((x > 1) && (x < 100)) || (x == 300)  
STYLE

It is poor style to compare a condition to true or false:

Poor style Better style
if (danger == true) {
    System.out.println("Run away!");
} 
if (danger) {
    System.out.println("Run away!");
} 
if (danger == false) {
    System.out.println("Relax.");
} 
if (!danger) {
    System.out.println("Relax.");
} 

The comparison is redundant and just looks silly.

Double negations (or worse) should be avoided:

Poor style Better style
if (!danger) {
    System.out.println("Stay here");
}
else {
    System.out.println("Run away!");
} 
if (danger) {
    System.out.println("Run away!");
}
else {
    System.out.println("Stay here");
}
if (!illegalMove(i, j)) {
    move(i, j);
} 
if (legalMove(i, j)) {
    move(i, j);
} 

To help avoid double negations, boolean methods should be given positive names such as legalMove or gameOver, not negative ones such as illegalMove or gameNotOver.