Java Reference
In-Depth Information
As you can see from studying the table in Display 3.6, most binary operators associ-
ate from left to right. But the assignment operators associate from right to left. So the
expression
number1 = number2 = number3
means
number1 = (number2 = number3)
which in turn is interpreted as the following fully parenthesized expression:
(number1 = (number2 = number3))
However, this fully parenthesized expression may not look like it means anything until
we explain a bit more about the assignment operator.
Although we do not advocate using the assignment operator = as part of a complex
expression, it is an operator that returns a value, just as + and * do. When an assignment
operator = is used in an expression, it changes the value of the variable on the left-hand
side of the assignment operator and also returns a value—namely, the new value of the
variable on the left-hand side of the expression. So (number2 = number3) sets number2
equal to the value of number3 and returns the value of number3 . Thus,
number1 = number2 = number3
which is equivalent to
(number1 = (number2 = number3))
sets both number2 and number1 equal to the value of number3 . It is best to not use
assignment statements inside of expressions, although simple chains of assignment
operators such as the following are clear and acceptable:
number1 = number2 = number3;
Although we discourage using expressions that combine the assignment operator
and other operators in complicated ways, let's try to parenthesize one just for practice.
Consider the following:
number1 = number2 = number3 + 7 * factor
The operator of highest precedence is * , and the operator of next-highest precedence is
+ , so this expression is equivalent to
number1 = number2 = (number3 + (7 * factor))
which leaves only the assignment operators to group. They associate right to left, so
the fully parenthesized equivalent version of our expression is
(number1 = (number2 = (number3 + (7 * factor))))
Search WWH ::




Custom Search