Why is `index = index ++` increment `index` not being indexed?
** Dup: What's the difference between X = X ++; vs X ++ ;? **
So, while I know you never do this in code, I'm still wondering:
public static void main(String[] args) {
int index = 0;
System.out.println(index); // 0
index++;
System.out.println(index); // 1
index = index++;
System.out.println(index); // 1
System.out.println(index++); // 1
System.out.println(index); // 2
}
Note that the third sysout
is still 1
. In my opinion, the string index = index++;
means "set the index to be indexed and then increment the index by 1" in the same way System.out.println(index++);
means "pass the index to the println method and then increase the index by 1".
However, it is not. Can anyone explain what is going on?
source to share
value++;
is an increment of posts.
int firtValue = 9;
int secondValue = firstValue++;
firstValue is now 10, but secondValue is 9, the value of firstValue before it was incremented.
Now pre-incremented:
int firtValue = 9;
int secondValue = ++firstValue;
firstValue and secondValue are now 10, fistValue is incremented and then its value is assigned to secondValue.
source to share
I've never tried anything like this, but I'm willing to be that the assignment happens after the increment.
So what really happens with regard to the compiler:
- Index score
- Save the index value for later
- Increase index value
- Assign the old index value, thereby destroying the increment.
source to share
You have to see what things are being evaluated.
in the following statement
index = index ++;
Three things happen 1) since this is the c ++ index, the value of the index is determined 2) the index is incremented, 3) the value that was determined in the first step is then assigned to the variable on the left side of the equation
source to share
See http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html for postfix evaluation rules.
Also see http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#39438 for info.
source to share