post increment operator java

srandpersonia picture srandpersonia · May 1, 2010 · Viewed 7.3k times · Source

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.

Answer

polygenelubricants picture polygenelubricants · May 1, 2010

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.


See also

  • JLS 15.14.2 Postfix Increment Operator

    "...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."