Java Reference
In-Depth Information
but higher precedence than the assignment operators, so the use of parenthe-
ses is frequently unnecessary. All of these operators associate from left to
right, but this fact is useless: In the expression a<b<6 , for example, the first <
generates a boolean and the second is illegal because < is not defined for bool-
ean s. The next section describes the correct way to perform this test.
1.5.2 logical operators
Java provides logical operators that are used to simulate the Boolean algebra
concepts of AND, OR, and NOT. These are sometimes known as conjunction ,
disjunction , and negation , respectively, whose corresponding operators are && ,
|| , and ! . The test in the previous section is properly implemented as a<b &&
b<6 . The precedence of conjunction and disjunction is sufficiently low that
parentheses are not needed. && has higher precedence than || , while ! is
grouped with other unary operators (and is thus highest of the three). The
operands and results for the logical operators are boolean . Figure 1.4 shows
the result of applying the logical operators for all possible inputs.
Java provides logi-
cal operators that
are used to simu-
late the Boolean
algebra concepts of
AND, OR, and NOT.
The corresponding
operators are && , || ,
and ! .
One important rule is that && and || are short-circuit evaluation operations.
Short-circuit evaluation means that if the result can be determined by examining
the first expression, then the second expression is not evaluated. For instance, in
Short-circuit evalu-
ation means that if
the result of a logi-
cal operator can be
determined
by examining the
first expression,
then the second
expression is not
evaluated.
x != 0 && 1/x != 3
if x is 0, then the first half is false . Automatically the result of the AND must
be false , so the second half is not evaluated. This is a good thing because
division-by-zero would give erroneous behavior. Short-circuit evaluation
allows us to not have to worry about dividing by zero. 2
figure 1.4
Result of logical
operators
x
y
x && y
x || y
!x
false
false
false
false
true
false
true
false
true
true
true
false
false
true
false
true
true
true
true
false
2. There are (extremely) rare cases in which it is preferable to not short-circuit. In such cases,
the & and | operators with boolean arguments guarantee that both arguments are evaluated,
even if the result of the operation can be determined from the first argument.
 
 
Search WWH ::




Custom Search