Java Reference
In-Depth Information
OPERATOR PRECEDENCE GROUP ASSOCIATIVITY
?: left
=, +=, −=, *=, /=, %=, <<=, >>=, >>>=, &=, |=, ^=right
Most of the operators that appear in the table you have not seen yet, but you will learn about them all in this topic even-
tually, and it is handy to have them all gathered together in a single precedence table that you can refer to when neces-
sary.
By definition, the postfix ++ operator changes the value of its operand after the other operators in the
expression in which it appears have been executed, despite its high precedence. In this case, precedence
determines what it applies to; in other words, the postfix ++ acts only on the variable that appears immedi-
ately before it. For this reason the expression numOranges+++numApples that we saw earlier in the chapter
is evaluated as (numOranges++) + numApples rather than numOranges + (++numApples) .
The sequence of execution of operators with equal precedence in a statement is determined by a property
called associativity. The operators that appear on the same line in Table 2-10 form a group of operators that
are either left-associative or right-associative . A left-associative operator attaches to its immediate left op-
erand. This results in an expression involving several left-associative operators with the same precedence
in the same expression being executed in sequence starting with the leftmost and ending with the right-
most. Right-associative operators of equal precedence in an expression bind to their right operand and con-
sequently are executed from right to left. For example, if you write the following statement
a = b + c + 10;
the left associativity of the group to which the + operator belongs implies that this is effectively
a = (b + c) + 10;
On the other hand, = and op= are right-associative, so if you have int variables a , b , c , and d each initial-
ized to 1, the statement
a += b = c += d = 10;
sets a to 12, b and c to 11, and d to 10. The statement is equivalent to:
a += (b = (c += (d = 10)));
NOTE Note that these statements are intended to illustrate how associativity works and are
not a recommended approach to coding.
You will probably find that you will learn the precedence and associativity of the operators in Java by
just using them in your programs, so don't spend time trying to memorize them. You may need to refer to
the table from time to time, but as you gain experience you will gain a feel for where the operators sit and
eventually you will automatically know when you need parentheses and when not.
Search WWH ::




Custom Search