Java Reference
In-Depth Information
Boolean Operators
Now that you have seen the logic behind the operators, let's look at the corre-
sponding programming syntax. Table 3.4 shows the Boolean operators available
in Java.
The & and && operators only differ in that the && will short-circuit when
the first Boolean expression is false. To demonstrate, consider the following
Boolean expression:
(a > 0) && (a < 1)
If a is not greater than 0, the first part of the expression is false. Because the
operation is and , we can now say that the entire expression will be false, no
matter what the result of the second expression is. In the case of using the two
ampersands &&, the expression will short-circuit and the (a < 1) will not be
checked.
There are many situations where short-circuiting is the desired result. For
example, consider the following expression:
(x != 0) && (y/x < 1)
If x is 0, then you do not want the second expression to be evaluated because
it involves integer division by zero, which causes a runtime exception and will
make your program crash. If x is not 0, the first part is true, and the second part
must be evaluated to determine the result of the entire Boolean expression.
Because we are assured that x is not zero, the division y/x is no problem.
In some situations, you might not want the short-circuit behavior.
In the following example, the second part of the expression contains
an operation that changes the value of the variable x:
(x != 0) && (x++ > 10)
I consider the preceding statement to be poor programming practice, but
it illustrates my point. If x is 0, then the x++ increment will not occur. If
you want the x++ to be evaluated in all situations, you would use the
single ampersand (&):
(x != 0) & (x++ > 10)
No matter if x is 0 or not, the expression (x++ > 10) will be tested.
In other words, the single ampersand guarantees that both Boolean
expressions will be checked. The same is true for the or operator (
).
Search WWH ::




Custom Search