Java Reference
In-Depth Information
Table 3.4
The Boolean Operators
OPERATOR
SYNTAX
short-circuit and
&&
and
&
short-circuit or
||
or
|
exclusive or
^
not
!
The or operator also has two versions. The || operator will short-circuit if
the first Boolean expression is true. (If the first part of the expression is true, it
does not matter what the second part evaluates to. The entire expression will
be true.)
For example, the following statement will short-circuit:
int x = 10;
(x > 0) || (x-- != 10)
The previous expression is true because the first part is true. What is x after
the code above? Because it short-circuits, x will still be 10. The second part of
the Boolean expression is not evaluated.
As with the single ampersand, &, you can use the single | to ensure that an
or expression never short-circuits:
int x = 10;
(x > 0) | (x-- != 10)
What is x after the code above? This time, no short-circuiting occurs and x
will be decremented to 9. The expression still evaluates to true because true or
false is true.
The not operator, !, may be placed at the beginning of any Boolean expres-
sion or variable. Consider the following statements:
short a = 10, b = 5;
boolean test = !(a > b);
Because a is greater than b, the expression in parentheses is true. The not
operator is then applied to true, which results in false (not true equals false);
therefore, the value of test is false.
Search WWH ::




Custom Search