Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

post increment operator java

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...