VinoTinto
asked on
i = i++
Why does this print 5 instead of 6?
int i = 5;
i = i++;
System.out.println(i);
int i = 5;
i = i++;
System.out.println(i);
The reasoning of this (I believe) is that primitives in Java are immutable.
so when you do i=i++;
it creates a new memory location for 'i' and points it to the original value (in this case 5)
then it takes the original memory location of i and increments it (in this case to 6) but since 'i' now points to a new memory location (which is pointing to 5) you will get 5 printed out.
On the other hand if you do:
i++; // instead of i=i++;
you are incrementing the original memory location.
I believe this is what happens. Please correct me if I am wrong.
CJ
so when you do i=i++;
it creates a new memory location for 'i' and points it to the original value (in this case 5)
then it takes the original memory location of i and increments it (in this case to 6) but since 'i' now points to a new memory location (which is pointing to 5) you will get 5 printed out.
On the other hand if you do:
i++; // instead of i=i++;
you are incrementing the original memory location.
I believe this is what happens. Please correct me if I am wrong.
CJ
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I am just thinking that i would be very interesting (and also very evil) to use this pattern within loops in commercial code. We guaranteed to foil the maintenance programmer. :D
:-)
I was told this is pretty much borrowed directly from C
CJ
I was told this is pretty much borrowed directly from C
CJ
ASKER
Thanks to both of you. Very good and detailled answer. Exactly what I was looking for.
i = ++i;