Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^458) | Exceptions and Additional Control Structures
sum = - - 1
means
sum = -(-1)
instead of the meaningless
sum = (- -) 1
This associativity makes sense because the unary “–” operation is naturally a right-to-left
operation.
A word of caution: Although operator precedence and associativity dictate the grouping
of operators with their operands, the precedence rules do not define the orderin which
subexpressions are evaluated. Java further requires that the left-side operand of a two-
operand operator be evaluated first. For example, if icurrently contains 5, the statement
j = ++i + i;
stores 12 into j. Let’s see why. The expression statement contains three operators: =,++, and
+. The ++operator has the highest precedence, so it operates just on i, not on the expression
i+i. The addition operator has higher precedence than the assignment operator, giving im-
plicit parentheses as follows:
j = (++i + i);
So far, so good. But now we ask this question: In the addition operation, is the left
operand or the right operand evaluated first? As we just saw, the Java language tells us
that the left-side operand is evaluated first. Therefore, the result is 6 + 6, or 12. If Java had
instead specified that the right-side operand comes first, the expression would have yielded
6 + 5, or 11.
In most expressions, Java’s left-side rule doesn’t have any surprising effects. But when
side effect operators such as increment and assignment are involved, you need to remem-
ber that the left-side operand is evaluated first. To make the code clear and unambiguous,
it’s best to write the preceding example with two separate statements:
i++;
j = i + i;
The moral here is that it’s best to avoid unnecessary side effects altogether.

Free download pdf