Boolean Expressions
A Boolean expression is a Java expression that, when evaluated, returns a Boolean value: true
or false
. Boolean expressions are used in conditional statements, such as if
, while
, and switch
.
The most common Boolean expressions compare the value of a variable with the value of some other variable, a constant, or perhaps a simple arithmetic expression. This comparison uses one of the following relational operators:
Operator |
Description |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
|
Returns |
A basic Boolean expression has this form:
expression relational-operator expression
Java evaluates a Boolean expression by first evaluating the expression on the left, then evaluating the expression on the right, and finally applying the relational operator to determine whether the entire expression evaluates to true
or false
.
For example, suppose you have declared two variables:
int i = 5;
int j = 10;
Here are a few simple expressions along with their results:
Expression |
Value |
Explanation |
|
|
The value of |
|
|
The value of |
|
|
|
|
|
|
|
|
|
|
|
|
if (i = 5)
Oops. That’s not allowed.