2

Possible Duplicate:
What is the difference between a += b and a =+ b , also a++ and ++a?
What is x after “x = x++”?

In Test1 i increments its value by 1 and return old value and keep its incremental value in i variable. But in Test2 i increments its value by 1 and return its old value and the increment also occurred. Are they make a copy of i for the increment which is not assigning in the i variable. What is the operational step in Test2.

Test1

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

Output 01

Test2

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

Output 0

Community
  • 1
  • 1
Sudeepta
  • 2,194
  • 4
  • 20
  • 24

3 Answers3

15

The statement i = i++ has well-defined behavior in Java. First, the value of i is pushed on a stack. Then, the variable i is incremented. Finally, the value on top the stack is popped off and assigned into i. The net result is that nothing happens -- a smart optimizer could remove the whole statement.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
3

i = i++; is the tricky construct, what it really does is something like the following:

int iOld = i;
i = i + 1;
i = iOld;

You want to use only i++; as a standalone statement.

millimoose
  • 39,073
  • 9
  • 82
  • 134
  • That is weird beacuse you would expected `i = i++;` to be the same as: `i = i = i + 1;`. Beacuse i++ alone means: `i = i + 1`; That does exlain however why a loop where `i = 0;` remains 0 and loops for etertnity when contructed like that. – Lealo Dec 01 '17 at 16:04
1

When the ++ operator appears after the variable, as in your example i++, the increment of i, happens after the operation is over. that's why the first print in the first example is zero, you haven't added yet, and then second one is 1.

the second example is the same as saving i, then incremeting it, and placing the original back.

i++

is an operator itself.

You could experiment the first one with ++i which will increase i before doing the printing action

La bla bla
  • 8,558
  • 13
  • 60
  • 109