0

Possible Duplicate:
What is x after “x = x++”?

I am shocked to see this output and want to know how it is working internally please help me.

int i=0;
i = i++;
System.out.println(i);
i=i++;
System.out.println(i);

Output is 0 and 0.

Community
  • 1
  • 1

1 Answers1

1

Change it to

int i=0;
i++;//note the removed i =
System.out.println(i);
i++;//note the removed i =
System.out.println(i);

and it will work as expected

See the Oracle documentation and their demo code, and to quote the most relevant part

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 version (result++) evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't really matter which version you choose. But if you use this operator in part of a larger expression, the one that you choose may make a significant difference.

Robin
  • 36,233
  • 5
  • 47
  • 99