Experiment 12: Assignment Associativity


Because the assignment symbol (=) is an actual operator that produces a value, the sequence of symbols

   Variable = Expression

is itself an expression that can appear to the right of an assignment operator. That is, a statement with the form

   w = x = y = z;

is a valid statements, and uses a technique sometimes called assignment chaining.

The question is, what happens when execution reaches this statement?

The answer depends on the associativity of the assignment operator. That is, if = is left associative, then the expression is evaluated as

   (((w = x) = y) = z)

but if assignment is right associative, then the expression is evaluated as

	(w = (x = (y = z)))

We can determine the answer with an experiment. If we initialize w, x, y and z to different values (say, 1, 2, 4 and 8), perform this assignment, and then display their values, the values that appear should provide us with enough information to determine whether assignment is left or right associative.

That is, suppose that w is 1, x is 2, y is 4, and z is 8. If = is left-associative, then when

   w = x = y = z;

is executed, the actions will occur in this order:

  1. w will be assigned the value of x (2);
  2. x will be assigned the value of y (4); and
  3. y will be assigned the value of z (8).

so that 2, 4, 8 and 8 will appear when the variable's values are displayed.

On the other hand, if = is right-associative, then when

   w = x = y = z;

is executed, the actions will occur in this order:

  1. y will be assigned the value of z (8);
  2. x will be assigned the value of y (8); and
  3. w will be assigned the value of x (8).

so that 8, 8, 8 and 8 will be displayed.

Modify Express.java as necessary to conduct this experiment and record your observations and conclusions in the space below:





You should now understand more fully how the assignment operator works, and the direction in which it associates.


Back to the Exercise List

Forward to the Next Experiment


Back to the Table of Contents

Back to the Introduction


Copyright 2000 by Prentice Hall. All rights reserved.