Programming and Problem Solving with Java

(やまだぃちぅ) #1
4.2 Conditions and Logical Expressions | 165

Precedence of Operators


In Chapter 3, we discussed the rules of precedence, which govern the evaluation of complex
arithmetic expressions. Java’s rules of precedence also apply to relational and logical oper-
ators. The following list shows the order of precedence for the arithmetic, relational, and log-
ical operators (with the assignment operator thrown in as well):


() Highest precedence
! unary– unary+ ++ -- (post)
++ -- (pre)
* / %
+ -
< <= > >=
== !=
&&
||
= Lowest precedence

Operators on the same line in the list have the same precedence. If an expression contains
several operators with the same precedence, most of the operators group (or associate) from
left to right. For example, the expression


a / b * c


means (a/ b) c, not a/ (b c). However, the !operator groups from right to left. Although you’d
never have occasion to use the expression


!!badData


It means !(!badData)rather than the useless (!!)badData. Appendix B gives the order of prece-
dence for all operators in Java. In skimming the appendix, you can see that a few of the op-
erators associate from right to left (for the same reason we just described for the !operator).
You can use parentheses to override the order of evaluation in Boolean expressions. If
you’re not sure whether parentheses are necessary, use them anyway.The compiler disregards
unnecessary parentheses. So, if they clarify an expression, use them. Some programmers
like to include extra parentheses when assigning a relational expression to abooleanvariable:


dataInvalid = (inputVal == 0);


The parentheses are not needed; the assignment operator has the lowest precedence of all
the operators we’ve just listed. So we could write the statement as


dataInvalid = inputVal == 0;


The parenthesized version, however, is more readable.

Free download pdf