Java Reference
In-Depth Information
The first operand, n!=0 , evaluates to false . Since && with a false operand
evaluates to false regardless of the value of the other operand, evaluation of the
expression terminates with the value false —without evaluating the second
operand.
Now evaluate the expression but with the operands of the conjunction
exchanged (in a state in which n is 0 ):
10/n>2 && n!=0
Since n is 0 , evaluation of 10 / n causes execution of the program to abort.
Division by 0 is not allowed.
Thus, changing the order of the operands in a conjunction can change the
value of the conjunction.
Evaluation of a conjunction b&&c is done using short-circuit evaluation : if
the first operand b is false , the result false is obtained without evaluating the
second operand.
We can give a definition of && using a non-Java “conditional expression”:
b&&c is equivalent to: ( if b then c else false )
which has the meaning: if b is true , then the result is whatever c is; otherwise,
the result is false . Actually, Java has such a conditional expression with a dif-
ferent notation, and we can define b&&c as:
b&&c is equivalent to: b ? c : false
In a similar fashion, disjunction || uses short-circuit evaluation; it is defined as:
b||c is equivalent to: b ? true : c
Short-circuit evaluation is used to protect an operation that might be unde-
fined in some states from being evaluated in those states. You have seen one
example of this: protection against division by 0 . Another operation that may
need protection is referencing an element of an array because the subscript may
not be in the range of the array. A third situation is protection against referring to
a field of a nonexistent object. Here are the schemas for these boolean expres-
sions:
if (n != 0 && ( boolean expression involving division by n)) …
if (n < b.length && ( boolean expression involving b[n])) …
if (obj != null && ( boolean expression involving obj.f)) …
Do not use | and & . Java has two “bit” operators, | and & , which in many situations give the same
result as || and &&. However, they are not evaluated in short-circuit mode. For
example, evaluation of n=0|x/0=5 causes a division-by-zero exception,
while evaluation of n=0||x/0=5 does not. The moral of this story is: stay
away from | and & and use || and && , unless you really are in a situation where
| or & are required.
Search WWH ::

Custom Search