Java Reference
In-Depth Information
second operand has. In an OR operation, if the first operand is true, the outcome of the
operation is true no matter what the value of the second operand. Thus, in these two cases
there is no need to evaluate the second operand. By not evaluating the second operand, time
is saved and more efficient code is produced.
The short-circuit AND operator is && , and the short-circuit OR operator is || . Their nor-
mal counterparts are & and | . The only difference between the normal and short-circuit
versions is that the normal operands will always evaluate each operand, but short-circuit
versions will evaluate the second operand only when necessary.
Here is a program that demonstrates the short-circuit AND operator. The program de-
termines whether the value in d is a factor of n . It does this by performing a modulus op-
eration. If the remainder of n / d is zero, then d is a factor. However, since the modulus
operation involves a division, the short-circuit form of the AND is used to prevent a divide-
by-zero error.
To prevent a divide-by-zero, the if statement first checks to see if d is equal to zero. If
it is, the short-circuit AND stops at that point and does not perform the modulus division.
Thus, in the first test, d is 2 and the modulus operation is performed. The second test fails
because d is set to zero, and the modulus operation is skipped, avoiding a divide-by-zero
Search WWH ::




Custom Search