Escolar Documentos
Profissional Documentos
Cultura Documentos
BASIC
index
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
&& || ! ^
What it means True if and only if both sides are true True if either side is true (or if both are true) Changes true to false, and false to true True if either side is true (but not both)
Example
wet && cold rich || famous !happy 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)
Better style
if (danger) { System.out.println("Run away!"); } if (!danger) { System.out.println("Relax."); }
The comparison is redundant and just looks silly. Double negations (or worse) should be avoided: Poor style
if (!danger) { if (danger) {
Better style
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.