Operator precedence

Figure 130. Operator precedence examples Slide presentation
Code
System.out.println(2 - 4 + 7);
// left-to-right:
// Equivalent to (2 - 4) + 7
System.out.println(2 + 3 * 5);
// Equivalent to 2 + (3 * 5)
Result
5
17

Figure 131. Operator precedence references Slide presentation

exercise No. 50

Evaluating a sum

Q:

Consider:

Code
int a = 3;
System.out.println(++a + a);
int a = 3;
System.out.println(a + ++a);
Result
8
7

Explain these two different outcomes.

A:

We consider the evaluation order for both snippets:

++a + a :
  1. a gets incremented from 3 to 4 by ++a. The values both of a and the ++a expression are thus 4.

  2. The value of ++a and a are being summed up by the binary + operator yielding 8.

a + ++a :
  1. The binary + operator takes the value 3 from its left operand a.

  2. Due to higher precedence of unary ++ over binary + the variable a gets incremented from 3 to 4: The value of the expression ++a is thus 4.

  3. The binary + operator takes the value 4 from its right operand ++a resulting in 7.