Java Reference
In-Depth Information
the effect is different. The whole logical expression is always evaluated, so even though the left-hand op-
erand of the & operator is false and the result is a foregone conclusion after that is known, the right-hand
operand (3*number - 27)>100) is still evaluated.
So, you can just use && all the time to make your programs a bit faster and forget about & , right? Wrong
— it all depends on what you are doing. Most of the time you can use && , but there are occasions when you
want to be sure that the right-hand operand is evaluated. Equally, in some instances, you want to be certain
the right-hand operand won't be evaluated if the left operand is false .
For example, the first situation can arise when the right-hand expression involves modifying a variable
— and you want the variable to be modified in any event. An example of a statement like this is:
if(++value%2 == 0 & ++count < limit) {
// Do something
}
Here, the variable count is incremented in any event. If you use && instead of & , count is incremented
only if the left operand of the AND operator is true . You get a different result depending on which operator
is used.
I can illustrate the second situation with the following statement:
if(count > 0 && total/count > 5) {
// Do something...
}
In this case, the right operand for the && operation is executed only if the left operand is true — that is,
when count is positive. Clearly, if you were to use & here, and count happened to be zero, you would be
attempting to divide the value of total by 0, which in the absence of code to prevent it would terminate the
program.
Logical OR Operations
The OR operators, | and || , apply when you want a true result if either or both of the operands are true .
The logical OR, || , works in a similar way to the && operator in that it omits the evaluation of the right-hand
operand when the left-hand operand is true . Obviously if the left operand for the || operator is true , the
result is true regardless of whether the right operand is true or false .
Let's take an example. A reduced entry ticket price is issued to under 16-year-olds and to those aged 65
or older; this could be tested using the following if :
if(age < 16 || age >= 65) {
ticketPrice *= 0.9; // Reduce ticket price by 10%
}
The effect here is to reduce ticketPrice by 10 percent if either condition is true . Clearly in this case,
both conditions cannot be true .
With an | or an || operation, you get a false result only if both operands are false . If either or both
operands are true , the result is true .
Exclusive OR Operations
Search WWH ::




Custom Search