Somenath Sinha Somenath Sinha - 2 months ago 6
Java Question

Where am I screwing up in the evaluation of this mathematical expression in Java?

My Code is:

int x=5,y=3;
x+=y*++x-x/y-y++;
System.out.println("Value = "+x);


My evaluation is as below:


x+=y*++x-x/y-y++

(x=5 | y=3)

x=x+(y*++x-x/y-y++)

(x=5 | y=3) | ++ and -- have highest priority

x=x+(y*6-x/y-3)

(x=6 | y=4) | * and / have next highest priority

x=x+(4*6-(6/4)-3)

(x=6 | y=4)

x=x+(24 -1 -3)

(x=6 | y=4)

x= 6+20

(x=6 | y=4)

x = 26.


However, when I evaluate the above in Java, the output turns out to be 18. What did I do wrong?

Additionally, is there any program online that can solve such problems as above with step by step analysis? If so, could you name some?

Answer

The expression is evaluated from left to right :

x += (y*++x)-(x/y) -(y++);
      3*6   - 6/3  - 3     == 18 - 2 - 3 == 13

so

x += 13 == 18 // since the original value of x is used here

Regarding the last part, the original value of x is used since that's the definition of compound assignment operators :

  • First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

  • Otherwise, the value of the left-hand operand is saved and then the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

  • Otherwise, the saved value of the left-hand variable and the value of the right-hand operand are used to perform the binary operation indicated by the compound assignment operator. If this operation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

  • Otherwise, the result of the binary operation is converted to the type of the left-hand variable, subjected to value set conversion (ยง5.1.13) to the appropriate standard value set (not an extended-exponent value set), and the result of the conversion is stored into the variable.