Search code examples
javaincrementprefixoperator-precedencepostfix-operator

Precedence of ++ and -- operators in Java


I read from the official tutorial of Java that prefix and postfix ++ -- have different precedences:

postfix: expr++ expr--

unary: ++expr --expr +expr -expr ~ !

Operators

According to the tutorial, shouldn't this

d = 1; System.out.println(d++ + ++d);

print out 6 (d++ makes d 2, ++d makes it 3) instead of 4?

I know the explanation of ++d being evaluated beforehand, but if d++ has higher precedence then ++d, why isn't d++ being first evaluated? And what is more, in what case should d++ shows that it has higher precedence?

EDIT:

I tried the following:

d = 1; System.out.println(++d * d++);

It returns 4. It seems that it should be 2*2, instead of 1*3.


Solution

  • The inside of the println statement is this operation (d++) + (++d)

    1. It is as follows, the value of d is read (d = 1)
    2. current value of d (1) is put into the addition function
    3. value of d is incremented (d = 2).

    4. Then, on the right side, the value of d is read (2)

    5. The value of d is incremented (now d = 3)
    6. Finally, the value of d (3) is put into the addition function

      thus 1 + 3 results in the 4

    edit: sorry for the format, I'm rather bad at using the list haha