post increment operator java

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

Leave a Comment