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.
Let's break down your own argument:
According to the author,
j=j++;
is similar to
temp=j; j=j+1; // increment j=temp; // then assign
Yes, you're right so far..., but here's where you got it wrong:
But
a=b++;
makes
b=1
. So it should've evaluated like this,a=b; // assign b=b+1; // then increment
WRONG! You're not applying the rule consistently! You've changed the order from increment then assign to assign then increment!!! It's actually evaluated like this:
temp=b;
b=b+1; // increment
a=temp; // then assign
Basically assignments of this form:
lhs = rhs++;
is similar to doing something like this:
temp = rhs;
rhs = rhs+1; // increment
lhs = temp; // then assign
Apply this to a = b++;
. Then apply it also to j = j++;
. That's why you get the results that you get.
What you did was you came up with your own interpretation of what a = b++;
does -- a WRONG interpretation that doesn't follow the above rule. That's the source of your confusion.
"...the value 1 is added to the value of the variable and the sum is stored back into the variable [...] The value of the postfix increment expression is the value of the variable before the new value is stored."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With