Java Reference
In-Depth Information
The exclusive OR results in true when its operands are different, so when one operand has the value true
and the other has the value false , the result is true . When both operands have the same value, either both
true or both false , the result is false . Thus the exclusive OR operator is useful on those rare occasions
when you want to establish whether or not two boolean values are different.
Boolean NOT Operations
The third type of logical operator, ! , applies to one boolean operand, and the result is the inverse of the op-
erand value. So if the value of a boolean variable, state , is true then the expression !state has the value
false , and if it is false , then !state evaluates to true . To see how the operator is used with an expression,
you could rewrite the code fragment you used to provide discounted ticket price as the following:
if(!(age >= 16 && age < 65)) {
ticketPrice *= 0.9; // Reduce ticket price by 10%
}
The expression (age >= 16 && age < 65) is true if age is from 16 to 64. People of this age do not
qualify for the discount, so the discount should be applied only when this expression is false . Applying the
! operator to the result of the expression does what you want.
You could also apply the ! operator in an expression that was a favorite of Charles Dickens:
!(Income > Expenditure)
If this expression is true , the result is misery, at least as soon as the bank starts bouncing your checks.
Of course, you can use any of the logical operators in combination when necessary. If the theme park
decides to give a discount on the price of entry to anyone who is younger than 12 years old and shorter than
48 inches tall, or to someone who is older than 65 and taller than 72 inches tall, you could apply the discount
with this test:
if((age < 12 && height < 48) || (age > 65 && height > 72)) {
ticketPrice *= 0.8; // 20% discount on the ticket price
}
The parentheses are not strictly necessary here, as && has a higher precedence than || , but adding the
parentheses makes it clearer how the comparisons combine and makes the code a little more readable.
WARNING Don'tconfusethebitwiseoperators & , | , ^ , and ! withthelogicaloperatorsthat
look the same. Which type of operator you are using in any particular instance is determined
by the type of operand with which you use it. The bitwise operators apply to integer types and
produce an integer result. The logical operators apply to operands that have boolean values
and produce a result of type boolean true or false . You can use both bitwise and logical
operators in an expression when it is convenient to do so.
Character Testing Using Standard Library Methods
Search WWH ::




Custom Search