Java Reference
In-Depth Information
The following example shows a comparison operator in use:
boolean hip;
int age = 36;
hip = age < 25;
The expression
age < 25
produces a result of either
true
or
false
, depending on the
value of the integer
age
. Because
age
is 36 in this example (which is not less than 25),
hip
is given the Boolean value
false
.
Logical Operators
Expressions that result in Boolean values, such as comparison operations, can be com-
bined to form more complex expressions. This is handled through logical operators,
which are used for the logical combinations
AND
,
OR
,
XOR
, and logical
NOT
.
For
AND
combinations, the
&
or
&&
logical operators are used. When two Boolean expres-
sions are linked by the
&
or
&&
operators, the combined expression returns a
true
value
only if both Boolean expressions are true.
Consider this example:
boolean extraLife = (score > 75000) & (playerLives < 10);
This expression combines two comparison expressions:
score > 75000
and
playerLives < 10
. If both of these expressions are true, the value
true
is assigned to
the variable
extraLife
. In any other circumstance, the value
false
is assigned to the
variable.
The difference between “&” and “&&” lies in how much work Java does on the com-
bined expression. If “&” is used, the expressions on either side of the “
&
” are evaluated
no matter what. If “&&” is used and the left side of the “&&” is false, the expression on
the right side of the “&&” never is evaluated.
For
OR
combinations, the “|” or “||” logical operators are used. These combined expres-
sions return a
true
value if either Boolean expression is true.
Consider this example:
boolean extralife = (score > 75000) || (playerLevel == 0);
This expression combines two comparison expressions:
score > 75000
and
playerLevel = 0
. If either of these expressions is true, the value
true
is assigned to the
variable
extraLife
. Only if both of these expressions are false will the value
false
be
assigned to
extraLife
.