Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java i++ operation explanation [duplicate]

Tags:

java

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

like image 606
Sudeepta Avatar asked Jul 15 '26 15:07

Sudeepta


2 Answers

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.

like image 83
Ernest Friedman-Hill Avatar answered Jul 20 '26 00:07

Ernest Friedman-Hill


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.

like image 39
millimoose Avatar answered Jul 20 '26 01:07

millimoose