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.
The key is what is returned from the operation.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With