Consider the below code:
public class Test {
public static void main(String args[]) {
long startTime = System.nanoTime();
for(int i = 1; i > 0; i++) {
System.out.println(i);
}
System.out.println(System.nanoTime() - startTime);
}
}
Output:
1
2
3
4
5
.
.
.
2147483643
2147483644
2147483645
2147483646
2147483647
16825610038948
I'm not able to get the value of startTime from Eclipse console, since there are huge amount of lines.
We call the above For-Loop as an Infinite Loop since i value is always greater than zero. Theoretically, the loop should not terminate. But since we use int, whose maximum value is 2147483647, the For-Loop terminates when we increment i, i.e. i++, when i = 2147483647.
So I was assuming that, when we increment i when i = 2147483647, the value of i will become negative or zero, so the condition becomes false, and the For-Loop terminates.
So to confirm, I tried the below code:
int i = 2147483647; // Maximum value of int
System.out.println(i++);
So if my assumption is correct, it should have printed any negative number or a zero value. but instead I got the following output:
2147483647
Here is my question/doubt:
When we increment i value, when i = 2147483647, the value of i is still the same, i.e. 2147483647. So how does the For-loop, in the above scenario, terminated without any error or exception?
It should've been ++i in your System.out.println();.
System.out.println(++i);
Your assumption is correct, when we increment i, when i = 2147483647, i becomes -2147483648.
i++ is different from ++i. First is a post-increment while second is a pre-increment.
i++ means
use the current value of
ifor the expression, then increment it
while the other, which is the one you are looking for, means:
increment the value of
iby 1, then use it in the expression
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With