"JavaRanch, where the deer and the Certified play" - David O'Meara
"JavaRanch, where the deer and the Certified play" - David O'Meara
Originally posted by Bob Young:
Interested in a puzzle with a twist? I came across this example and it took me awhile to get a grasp on it.
public class Test {
public static void main(String[] args) {
int i = 0;
i = i++;
i = i++;
i = i++;
System.out.println("i = " + i);
}
}
output is 0 (zero). Not the possibly expected value of 3! Following the rules for the increment operator it almost makes sense.
i++ first evaluates i(as 0), assigns the result back to i(which is 0). The twist is that the increment never seems to happen. You can see this by changing i to say -1. and the result will be -1, change it to 10 and the result will be 10, add more i = i++; lines and you will get the initial value of i. Remove all but one line of i = i++; and you still get whatever the initial value of i is set to.
One question is why is the increment lost? If you take a slightly different code as follows the increment will happen as it should.
public class Test {
public static void main(String[] args) {
int j, i = 3;
j = i++ - i++; // j= i++ (1st) - i++ (2nd)
System.out.println("i = " + i);
System.out.println("j = " + j);
}
}
results are i = 5 and j = -1. The 1st i++ is evaluated as - initial value of i is 3 then the increment to 4 happens. The 2nd i++ is evaluated as - initial value of i is now 4 and then
the increment to 5 happens. Here the incrementing is happening as the evaluation of the code is moving down the line of code. Which all makes sense. All this explaination was needed to
show that the incrementing is taking place right after the evaluation of each expression (i++) while in the very first example I believe that the incrementing is somehow not being performed.
Any thoughts as to why?
"JavaRanch, where the deer and the Certified play" - David O'Meara
<UL TYPE=SQUARE><I><LI>Ryan Burgdorfer<BR><LI>Java Acolyte</I></UL>
"JavaRanch, where the deer and the Certified play" - David O'Meara
Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters? |