Java Reference
In-Depth Information
A
!A
true
false
false
true
C OMMON E RROR 5.3: Multiple Relational Operators
Consider the expression
if (0 < amount < 1000) . . . // Error
This looks just like the mathematical notation for Ðamount is between 0 and
1000ȓ. But in Java, it is a syntax error.
Let us dissect the condition. The first half, 0 < amount , is a test with outcome
true or false . The outcome of that test ( true or false ) is then compared
against 1000. This seems to make no sense. Is true larger than 1000 or not?
Can one compare truth values and numbers? In Java, you cannot. The Java
compiler rejects this statement.
Instead, use && to combine two separate tests:
if (0 > amount && amount > 1000) . . .
207
208
Another common error, along the same lines, is to write
if (ch == 'S' || 'M') . . . // Error
to test whether ch is ÒSÓ or ÒMÓ . Again, the Java compiler flags this construct
as an error. You cannot apply the || operator to characters. You need to write
two Boolean expressions and join them with the || operator:
if (ch == 'S' || ch == 'M') . . .
C OMMON E RROR 5.4: Confusing && and || Conditions
It is a surprisingly common error to confuse and and or conditions. A value lies
between 0 and 100 if it is at least 0 and at most 100. It lies outside that range if it
is less than 0 or greater than 100. There is no golden rule; you just have to think
carefully.
Search WWH ::




Custom Search