Result of function that includes pre- and post-increment differs

I had to understand some code which mixes pre- and post-increments in functions. There was one thing that confused me.

So I tried to test some smaller function. But I could not explain following behaviour:

int i = 1;
i = i++ * ++i * 2;
System.out.println("i = " + i);
int x = 1;
x = ++x * x++ * 2;
System.out.println("x = " + x);

The expected output was:

 i = 8
 x = 8

But actually is:

 i = 6
 x = 8

Can someone tell me why?

2
Leave a Reply

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

i++ * ++i * 2 –> 1 * 3 * 2 –> 6 ++x * x++ * 2 –> 2 * 2 * 2 –> 8 Important values in bold. The difference between the prefix and postfix increment when returning values in Java can be better summarized by Oracle themselves (my bold again for highlighting purposes): The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The code result++; and ++result; will both end in result being incremented by one. The only difference is that the prefix version (++result) evaluates to the incremented value, whereas the postfix… Read more »

Jason
Guest

Post-increment increases the value of i but does not immediately assign the new value of i. Pre-increment increases the value of i and is immediately assigned the new value. Thus, in your example for y, after i++, i has become 2 but it is still holding on to the previous value of 1. When ++i occurs, i with the value of 2 will be increased by 1 and simultaneously, assigned the new value of 3. Therefore, 1 * 3 * 2 gives us the value 6 for y. The same goes for x, when ++x occurs, x is immediately assigned… Read more »