Java Reference
In-Depth Information
In mathematics, this expression would make sense and would test whether x is
between 1 and 10 inclusive. However, the expression doesn't make sense in Java.
You can only use the logical AND and OR operators to combine a series of Boolean
expressions. Otherwise, the computer will not understand what you mean. To express
the “1 or 2 or 3” idea, combine three different Boolean expressions with logical ORs:
if (x == 1 || x == 2 || x == 3) {
doSomething();
}
To express the “between 1 and 10 inclusive” idea, combine two Boolean expres-
sions with a logical AND :
if (1 <= x && x <= 10) {
doSomethingElse();
}
Now that we've introduced the AND, OR, and NOT logical operators, it's time to
revisit our precedence table. The NOT operator appears at the top, with the highest
level of precedence. The other two logical operators have fairly low precedence,
lower than the arithmetic and relational operators but higher than the assignment
operators. The AND operator has a slightly higher level of precedence than the OR
operator. Table 5.4 includes these new operators.
According to these rules of precedence, when Java evaluates an expression like
the following one, the computer will evaluate the NOT first, the AND second, and then
the OR .
if (test1 || !test2 && test3) {
doSomething();
}
Table 5.4
Java Operator Precedence
Description
Operators
unary operators
!, ++, --, +, -
multiplicative operators
*, /, %
additive operators
+, -
relational operators
<, >, <=, >=
equality operators
==, !=
logical AND
&&
logical OR
||
assignment operators
=, +=, -=, *=, /=, %=, &&=, ||=
 
Search WWH ::




Custom Search