Consider the snippet:
int a = 1, b = 1, c = 1;
System.out.println(a + ++a);
System.out.println(b++ + ++b);
System.out.println(c++ + c);
The output is:
3
4
3
This is what I think is happening, but the output doesn't match up:
1. ++a -> +a -> 4 = 2 + 2
2. ++b -> +b -> 4 = 2 + 2
3. c -> +c -> 2 = 1 + 1
Unary post and pre-increment have higher precedence than addition:
b = 1
, b
is initialized to 1.b++
, b
's current value in the equation is 1, then b
is incremented.++b
, b
was incremented due to post-increment, so it's 2. Now it's incremented again due to pre-increment and its value in the equation is 3.1 + 3
is 4.The thing is, pre-increment increments the variable, then returns it thus in ++1
, the value is incremented, then that is returned, and evaluates to 2. With post-increment, the variable value is returned, then incremented. Thus 1++
will evaluate to 1, then increment to 2 on later reference. So:
b++ + ++b ^^^ post-increment, evaluates to 1
1 + ++b ^^^ pre-increment, due to post-increment is 2, then pre-increments and evaluates to 3
1 + 3 ^^^^^ evaluates to 4
This applies to the first and third examples too. For a + ++a
, ++a
has higher precedence. First, a
is evaluated, which is 1 at this point, then ++a
is evaluated as it has higher precedence, where a
is incremented, then the value returns and evaluates to 2. Then, addition is evaluated, which looks like this:
a + ++a ^ nothing, evaluates to 1
1 + ++a ^^^ pre-increment, evaluates to 2
1 + 2 ^^^^^ evaluates to 3
In the third example, c++ + c
, c
is post-incremented so it evaluates to 1, then increments. The last c
is then 2 and looks like this:
c++ + c ^^^ post-increment, evaluates to 1
1 + c ^ nothing, due to post-increment is 2 and evaluates to 2
1 + 2 ^^^^^ evaluates to 3
Thus the output:
3
4
3
It should be noted that precedence does not dictate evaluation order. Precedence only changes parenthesization of an expression. Evaluation order in Java is always left to right as ajb comments, unlike C/C++, see JLS 15.7.