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);
}
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);
}
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
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