Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 512
zw324 Avatar asked Jun 16 '11 14:06

zw324


1 Answers

The key is what is returned from the operation.

  • x++ changes the value of x, but returns the old x.
  • ++x changes the value of x, and returns the new value.
d=1
System.out.println(d++ + ++d); // d is 1
System.out.println(1 + ++d); // d is 2
System.out.println(1 + 3); // d is 3

Prints 4

like image 78
joeslice Avatar answered Oct 09 '22 00:10

joeslice