Java Reference
In-Depth Information
With an | or an || operation, you only get a false result if both operands are false . If either or
both operands are true , the result is true .
Boolean NOT Operations
The third type of logical operator, ! , takes one boolean operand and inverts its 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 becomes true . To see how the operator is used with an expression, we could
rewrite the code fragment we used to provide discounted ticket price as:
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 only be applied when this expression is false .
Applying the ! operator to the result of the expression does what we want.
We 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 if necessary. If the theme park decides to
give a discount on the price of entry to anyone who is under 12 years old and under 48 inches tall, or
someone who is over 65 and over 72 inches tall, you could apply the discount with the 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 it a little more readable.
Don't confuse the bitwise operators & , | , and ! , with the logical operators that 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 if it is convenient to do so.
Search WWH ::




Custom Search