Java Reference
In-Depth Information
This makes some sense because the test is doing something useful, in that it
switches the meaning of the boolean variable (evaluating to true if the variable is
false and evaluating to false if the variable is true ). But the negation operator is
designed to do this kind of switching of boolean values, so this test is better written
as follows:
if (!negative) {
...
}
You should get used to reading the exclamation mark as “not”, so this test would
be read as “if not negative.” To those who understand Boolean Zen, that is a more
concise way to express the test than to test whether negative is equal to false .
Negating Boolean Expressions
Programmers often find themselves needing to form the negation of a complex
Boolean expression. For example, it is often easiest to reason about a loop in terms of
an exit condition that would make us want to stop the loop, but the while loop
requires us to express the code in terms of a continuation condition. Suppose that you
want to write a loop that keeps prompting the user for an integer until that integer is a
two-digit number. Because two-digit numbers range from 10 to 99, you can use the
following lines of code to test whether a number has exactly two digits:
number >= 10 && number <= 99
To put this in a while loop, we have to turn the test around because the while
loop test is a continuation test. In other words, we want to stay in the loop while this
is not true (while the user has not yet given us a two-digit number). One approach is
to use the logical NOT operator to negate this expression:
while (!(number >= 10 && number <= 99))
Notice that we need to parenthesize the entire Boolean expression and then put the
NOT operator in front of it. While this approach works, it is generally considered bad
style. It is best to simplify this expression.
A general approach to simplifying such expressions was formalized by the British
logician Augustus De Morgan. We can apply one of two rules that are known as De
Morgan's laws .
Table 5.5 shows De Morgan's laws. Notice that when you negate a Boolean expres-
sion, each operand is negated ( p becomes !p and q becomes !q ) and the logical opera-
tor flips. Logical OR becomes logical AND and vice versa when you compute the
negation.
 
Search WWH ::




Custom Search