Experiment 7: Operator Associativity

You may have wondered what happens when the next operator to be applied could be either of two operators that have the same precedence level. For example, in the expression:

```   8 - 4 - 2
```

if the leftmost subtraction is performed first, then the expression evaluates to

```   (8 - 4) - 2 = 4 - 2 = 2
```

while if the rightmost subtraction is performed first, then the expression evaluates to

```   8 - (4 - 2) = 8 - 2 = 6
```

Thus, we see again that the order in which operators are applied determines the value of the expression. However, some characteristic other than precedence must be used in such situations, because each of the operators in question have the same precedence level.

This new characteristic is called operator associativity. More precisely, in an expression

```	x D1 y D2 z
```

where D1 and D2 are two operators with the same precedence level, if D1 is applied before D2, then D1 and D2 are described as left-associative, but if D2 is applied before D1, then they are described as right-associative. That is, the expression

```   8 - 4 - 2
```

will evaluated to 2 if - is left-associative, but will evaluate to 6 if - is right-associative. Use your sample program to find out the associativity of the - operator and report it below:

What is the associativity of the division operator /?

The associativity of the addition and multiplication operators are more difficult to determine, because the associativity property holds for these operators, namely:

```   (x + y) + z == x + (y + z)
```

and

```   (x * y) * z == x * (y * z)
```

So we'll just tell you what you might have guessed: each of the Java arithmetic operators +, -, *, / and % are left-associative, as are the majority of the Java operators. However, not all of them are, as we shall see in a later experiment.

To see a complete list of Java operators, their precedence levels and their associativities, see Appendix C of Java: An Introduction To Computing (the textbook for which this manual was written.)

You should now understand what operator associativity is, and how Java uses it to determine the order in which operators of the same precedence are applied within an expression.

Back to the Exercise List

Forward to the Next Experiment