-2

Based on the Oracle: Operator Doc Oracle

The preference of postfix incr and decr operator is higher than prefix operators.

But when I try this example:

int x = 1;
System.out.println(++x * x++); // prints 4

x=1;
System.out.println(x++ * ++x); // prints 3

If we go as the operators precedence, the output should be : 3 and 3 instead of 4 and 3.

Any help is appreciated.

azro
  • 53,056
  • 7
  • 34
  • 70
Array
  • 11
  • 3
  • 1
    [Operands are evaluated left-to-right, always](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.7). Precedence is not related to evaluation order. – Andy Turner Aug 22 '17 at 06:56
  • ...they're supposed to behave differently. – Powerlord Aug 22 '17 at 06:59
  • @Array Please consider accept an answer, it's how a forum works, by give points to those who spend time to answer you ;) – azro Aug 22 '17 at 11:37

1 Answers1

1

This is only post/pre increment element :

(++x * x++);
++x = 1 becomes 2 and use 2 for value
x++ = use 2 for value, and then 2 becomes 3
2*2 = 4

(x++ * ++x);
x++ = use 1 for value, and then 1 becomes 2
++x = 2 becomes 3 and use 3 for value
1*3 = 3

pre-increment : increment the value and use the new one for compute

post-increment : remember the old value, used for this calculation, and then increment

azro
  • 53,056
  • 7
  • 34
  • 70