-7

I executed the code and output was 19, but I don't understand why.

public static void main(String[] args) 
{
    int x = 0;
    x = (x = 1) + (x = 2) * (++x) * (x++);
    System.out.println(x);
}
Eran
  • 387,369
  • 54
  • 702
  • 768
mahdi
  • 184
  • 11

3 Answers3

8

You evaluate the operands from left to right, and then evaluate the multiplication operators before the addition operator:

x = (x = 1) + (x = 2) * (++x)  *      (x++);

       1    +    (2    *   3   *       3     )  = 19

    assignment          pre            post
    operator            increment      increment
    returns the         returns the    returns the
    assigned value      incremented    value before
                        value          it was incremented
Eran
  • 387,369
  • 54
  • 702
  • 768
2

its evaluated like this -

1+2*3*3

(x=1) - first x is set t 1
(x=2) - then x is set to 2
(++x) - then x is incremented to 3; pre-increment and affects the equation in this case (x++) - the last was post increment; no effect on the equations

Razib
  • 10,965
  • 11
  • 53
  • 80
2

as per my knowledge:

1 + 2*3*3 = 19