Java Reference
In-Depth Information
(Note that there is no case where two operators have equal precedence but one
associates from left to right while the other associates from right to left. That must be
true or else there would be cases with conflicting instructions for inserting parentheses.)
The association of operands with operators is called binding . For example, when
parentheses determine which two expressions (two operands) are being added by
a particular + sign, that is called binding the two operands to the + sign. A fully
parenthesized expression accomplishes binding for all the operators in an expression.
These examples should make it clear that it can be risky to depend too heavily on
the precedence and associativity rules. It is best to include most parentheses and to omit
parentheses only in situations where the intended meaning is very obvious, such as a
simple combination of * and + , or a simple chain of && 's or a simple chain of || 's. The
following examples have some omitted parentheses, but their meaning should be clear:
binding
rate * time + lead
(time < limit) && (yourScore > theirScore) && (yourScore > 0)
(expenses < income) || (expenses < savings) || (creditRating > 0)
Notice that the precedence rules include both arithmetic operators such as + and *
as well as Boolean operators such as && and || . This is because many expressions
combine arithmetic and Boolean operations, as in the following simple example:
(number + 1) > 2 || (number + 5) < -3
If you check the precedence rules given in Display 3.6, you will see that this expression
is equivalent to
(((number + 1) > 2) || ((number + 5) < (-3)))
because > and < have higher precedence than || . In fact, you could omit all the
parentheses in the above expression and it would have the same meaning (but would
be less clear).
It might seem that once an expression is fully parenthesized, the meaning of the
expression is then determined. It would seem that to evaluate the expression, you (or
the computer) simply evaluate the inner expressions before the outer ones. So, in
((number + 1) > 2) || ((number + 5) < (-3))
first the expressions (number + 1) , (number + 5) , and (-3) are evaluated (in any
order), then the > and < are evaluated, and then the || is applied. That happens to
work in this simple case. In this case, it does not matter which of (number + 1) ,
(number + 5) , and (-3) is evaluated first, but in certain other expressions it will be
necessary to specify which subexpression is evaluated first. The rules for evaluating a
fully parenthesized expression are (and indeed must be) more complicated than just
evaluating inner expressions before outer expressions.
 
Search WWH ::




Custom Search