# Boolean Expressions

### The boolean Type

Variables of boolean type have only two values: "true" and "false"

Arithmetic comparisons result in boolean values. For example:

boolean b1 = (5 > 3);                 // b1 = true;
boolean b2 = (2 <= 1);                // b2 = false;

boolean radiusIsPositive = (r > 0);   // could be true
// or false - it
// depends on what
// r is.


### Comparison Operators

Comparison operators compare a pair of values (possibly numbers, characters, or boolean values) and return a boolean value.

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

### Boolean Operators

Some operators perform "logic operations", operating on one or more Boolean values and resulting in a Boolean value. These are called Boolean operators.

 Boolean Operator Name ! not && and || or ^ exclusive or

#### Truth Table for the "not" operator (!)

 p !p T F F T

Examples

boolean b1 = !(1 > 2);  \\ b1 = true, as (1 > 2) is false
boolean b2 = !(1 > 0);  \\ b2 = false, as (1 > 0) is true


#### Truth Table for the "and" operator (&&)

 p q p && q T T T T F F F T F F F F

Examples

boolean b1 = (3 > 2) && (5 >= 5);  \\ b1 = true, as
\\ both inequalities
\\ are true

boolean b2 = (3 > 2) && (5 > 5);   \\ b2 = false, as
\\ (5 > 5) is false


#### Truth Table for the "or" operator (||)

 p q p || q T T T T F T F T T F F F

Examples

boolean b1 = (2 > 3) || (5 > 5);  \\ b1 = false, as
\\ both inequalities
\\ are false

boolean b2 = (3 > 2) || (5 > 5);  \\ b2 = true, as at
\\ least one of the
\\ inequalities is true


#### Truth Table for the "exclusive or" operator (^)

 p q p ^ q T T F T F T F T T F F F

Examples

boolean b1 = (2 > 3) ^ (5 > 5);   \\ b1 = false, as
\\ both inequalities
\\ are false

boolean b2 = (3 > 2) ^ (5 > 5);   \\ b2 = true, as
\\ exactly one of the
\\ inequalities is true

boolean b3 = (3 > 2) ^ (5 > 4);   \\ b3 = false, as
\\ both inequalities
\\ are true


A Boolean expression is an expression that evaluates to a Boolean value. The mathematics of these logical operators and expressions is called Boolean Algebra, and was developed by George Boole in 1854.

### Shortcut Evaluation of Boolean Expressions

Java uses "shortcut evaluation" when it attempts to evaluate a Boolean expression. In other words, the evaluation of the expression stops as soon as the result is known.

For example:

boolean b = (3 < 2) && ( 1/0 < 5 ); \\ b = false
\\ the expression on the right
\\ is never evaluated

boolean b = (3 > 2) && ( 1/0 < 5 ); \\ RUN-TIME ERROR
\\ due to the division
\\ by zero