Java – How ‘a += a++ * a++ * a++’ is Evaluated

javaoperator-precedencepost-increment

I came across this problem in this website, and tried it in Eclipse but couldn't understand how exactly they are evaluated.

    int x = 3, y = 7, z = 4;

    x += x++ * x++ * x++;  // gives x = 63
    System.out.println(x);

    y = y * y++;
    System.out.println(y); // gives y = 49

    z = z++ + z;
    System.out.println(z);  // gives z = 9

According to a comment in the website, x += x++ * x++ * x++ resolves to x = x+((x+2)*(x+1)*x) which turns out to be true. I think I am missing something about this operator precedence.

Best Answer

Java evaluates expressions left to right & according to their precedence.

int x = 3, y = 7, z = 4;

x (3) += x++ (3) * x++ (4) * x++ (5);  // gives x = 63
System.out.println(x);

y = y (7) * y++ (7);
System.out.println(y); // gives y = 49

z = z++ (4) + z (5);
System.out.println(z);  // gives z = 9

Postfix increment operator only increments the variable after the variable is used/returned. All seems correct.

This is pseudocode for the postfix increment operator:

int x = 5;
int temp = x;
x += 1;
return temp;

From JLS 15.14.2 (reference):

The value of the postfix increment expression is the value of the variable before the new value is stored.

Related Question