Boolean Expressions
Boolean Expressions
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:
Name of
Operator What it means Example
operator
True if and only if both
&& and wet && cold
sides are true
True if either side is true rich || famous
|| or
(or if both are true)
Changes true to false, and
! not !happy
false to true
True if either side is true walking ^
^ exclusive or
(but not both) ridingBus
Parentheses can be used for grouping the parts of complex boolean expressions. For
example:
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:
These have the obvious meanings, and can be combined with the boolean operators. For
example:
Boolean expressions are most often used as conditions (as in the examples above).
However, they may be used other places as well, for example:
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
} }
System.out.println("Relax."); System.out.println("Relax.");
} }
if (!danger) { if (danger) {
} }
else { else {
} }
} }
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.