0
int i = 0;
while(i < 5){
    i = i++;
    System.out.print(i);
}

The output is 000000... infinite

int i = 0;
while(i < 5)
{
    i = ++i;
    System.out.print(i);
}

The output is 12345

viren shah
  • 183
  • 2
  • 8
  • 3
    `i` is assigned the existing value of `i` before `i++` – Scary Wombat Mar 23 '17 at 05:02
  • see http://stackoverflow.com/questions/2371118/how-do-the-post-increment-i-and-pre-increment-i-operators-work-in-java – Scary Wombat Mar 23 '17 at 05:04
  • after assigned old value to i, i is incrementing as post increment operator use then why next line i value not changed? – viren shah Mar 23 '17 at 05:12
  • The order of assignment and post increment is not what you assume. The assignment of the old value occurs after the post increment operator. – Thomas Kläger Mar 23 '17 at 05:18
  • I think this is NOT a duplicate, but it is a valid question to ask as to why the variable i never incremented, and I find the answers provided so far missed the mark. – ndlu Mar 23 '17 at 05:25
  • @ndlu i is incremented (through the post increment operator) but **after that** the assignment of the old value (before the post increment) overwrites the incrmeneted value. What is unclear about that ordering? – Thomas Kläger Mar 23 '17 at 05:43
  • 1
    @ndlu: the snippet `i=i++;` is executed is `{int tmpi=i; i++; i=tmpi;}` and this is required through the language specification. You seem to assume that it is executed and `i=i; i++;` and this assumption is wrong. – Thomas Kläger Mar 23 '17 at 05:48
  • In post increment value incrementing after assign a old value – viren shah Mar 23 '17 at 05:49
  • @Thomas Kläger - your breakdown example is exactly what I was looking for. Thanks. viren shah hope this makes sense to you. – ndlu Mar 23 '17 at 05:54

1 Answers1

0

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.

From this link.

++i returns i+1 but i++ returns i.

kingsj0405
  • 149
  • 14