-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
  • 374,785
  • 51
  • 663
  • 734
mahdi
  • 184
  • 10

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
  • 374,785
  • 51
  • 663
  • 734
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,521
  • 10
  • 50
  • 75
2

as per my knowledge:

1 + 2*3*3 = 19