i and i=i++ in for loop java
Solution 1
See this brilliant answer:
x = x++;
is equivalent to
int tmp = x;
x++;
x = tmp;
From this question.
Solution 2
i = i++
is a postfix increment operator - it increments i
, then returns it to its original value (because the i++
essentially "returns" the value of i
before it was incremented.)
i = ++i
would work since it's a prefix increment operator, and would return the value of I after the increment. However, you probably just want to do i++
there without any extra assignment as you do in the first run - it's (essentially) shorthand as it is for i = i+1
.
Solution 3
What is happening happens because java is pass-by-value.
In the first loop, i
is getting incremented in the i++
statement, however, in the second loop what is happening is that i
gets pointed to a new memory location that stores the value of i
(in this case 0) and then increments the old location.
To visualise:
i => 0x00000001 // 0
for() {
i => 0x00000002 <- 0 // store old i value (0) in new location
0x00000001++ // Increment the value stored at the old location
// Cause there is no longer a reference to 0x00000001,
// it will get garbage collected and you will be left with
// i => 0x00000002
And it will keep doing that, assigning the old value to a new location and incrementing the old value for each pass of the loop
Solution 4
i = i++;
is equivalent to,
int temp = i; // temp = 0
i++; // i=1
i = temp; // i = 0
Solution 5
i=i++;
will never increment i because the ++ is processed after the i=i.
you could see it like this:
int i=0;
for(int k=0;k<10;k++){
int j = 0;
i = j;
j = j + 1;
}
vivek shetty
Updated on September 15, 2022Comments
-
vivek shetty over 1 year
What is the logic behind this behaviour?
int i=0; for(int k=0;k<10;k++){ i++; } System.out.println("i="+i); Output=10; //Exepcted int i=0; for(int k=0;k<10;k++){ i=i++; } System.out.println("i="+i); Output=0; //Surprised :)
Can anybody throw some light on above functionality?