Link to home
Start Free TrialLog in
Avatar of VinoTinto
VinoTinto

asked on

i = i++

Why does this print 5 instead of 6?
          int i = 5;
          i = i++;
          System.out.println(i);
Avatar of girionis
girionis
Flag of Greece image

 Because it is post increment. It increments the variable i after it assigns the value to it. To print 6 you have to do:

  i = ++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
ASKER CERTIFIED SOLUTION
Avatar of girionis
girionis
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
 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
Avatar of VinoTinto
VinoTinto

ASKER

Thanks to both of you. Very good and detailled answer. Exactly what I was looking for.