Precedence and Associativity in Java

In this class, We discuss Precedence and Associativity in Java.

The reader should have prior knowledge of expressions. Click Here.

We take an example and understand precedence and associativity.

Example:

int a = 9, b = 5, c= 2, d;

d = a+ b * c;

During the evaluation, first, consider the precedence of the operator.

In Java, * has the highest precedence over +.

Precedence means priority.

The star operator should be evaluated first in the expression a+ b * c.

b * c evaluated first. b * c = 10.

After that evaluation, go with +.

9 + 10 = 19.

d = 19.

Example 2:

d = a + b * c * a;

here * the operator is mentioned twice.

Whenever we have operators with the same precedence, we check for associativity.

Associativity tells us about the way of execution.

Associativity for * is left to right.

b*c will execute first.

b* c = 10 then we get a + 10 * a.

Now 10 * a is evaluated. 10 * 9 = 90

Finally a + 90 = 99

The below table shows the precedence and associativity table for all the operators.

Example 3:

int a = 9, b = 5, c= 2, d;

d = a+ b + (c+a*a*b)

From the precedence, table brackets have the highest precedence.

The expression in the bracket will evaluate first.

c + a * a* b = 407

Now a + b + 407 = 421