views:

251

answers:

3

I can't make heads or tails of the following code from "java puzzlers" by joshua bloch.

public class Test22{
 public static void main(String args[]){
  int j=0;
  for(int i=0;i<100;i++){ 
    j=j++;
  }
  System.out.println(j); //prints 0

  int a=0,b=0;
  a=b++;
  System.out.println(a);
  System.out.println(b); //prints 1


 }
}

I can't get the part where j prints 0. According to the author,

j=j++

is similar to

temp=j;
j=j+1;
j=temp;

But

a=b++

makes b 1. So it should've evaluated like this,

a=b
b=b+1

By following the same logic, shouldn't

j=j++

be evaluated as,

j=j
j=j+1

Where does the temp come into picture here? Any explanations would be much appreciated. << I'm breaking my head over this. ;)>> Thanks in advance.

+2  A: 

j++ will use the old value of j and then it will increment it. But when it overwrites the left hand side, it will use the old value of j.

It is similar to :

temp=j;
j += 1; 
j=temp;     // take the old value of j.
fastcodejava
+11  A: 
polygenelubricants
Wow that's a nice explanation.Thanks a lot mate.
srandpersonia
Yeah, good explanation.
fastcodejava
+8  A: 

The post increment operator implicitly uses a temp variable. This allows it to return one value while setting its argument to another. That's why

a = b++;

Can increment b, but set a to the old value of b. The same thing is going on with

j = j++;

The variable is incremented on the right hand side, but it's then set back to the old value when the assignment takes place.

Bill the Lizard
I had a different perspective from this explanation. Thanks for your time mate.
srandpersonia