Surprising difference

exercise No. 225

Q:

You have learned to replace expressions like e.g. b = b * 4 by b *= 4. The following two code snippets should thus be equivalent:

Code Output
int a = 3, b = 6;
b = b * a / 2;
System.out.println("b = " + b);
b = 9
int a = 3, b = 6;
b *= a / 2;
System.out.println("b = " + b);
b = 6

Explain the different outcome.

A:

The difference is being caused by the *= operator's behaviour with respect to the order of evaluation. The first expression b = b * a / 2 containing two left-associative operators * and / may be rewritten as b = ((b * a) / 2). We thus get 18 / 2 being equal to 9.

The second expression b *= a / 2 is equivalent to b = (b * (a / 2)). Since the integer division 3 / 2 results in 1 we get the final result 6.