Java – why is this loop not infinite
•
Java
See English answer > why does increasing a Java int eventually result in a negative number? 4
Why is there a one second gap between the start and end messages in the following code?
System.out.println("Start:" + LocalTime.Now()); for (int i = 0; i > -1; i++) { /*Infinite looP*/ } System.out.println("End :" + LocalTime.Now());
I tried to find out if DCE needed time to process this type of code, but I couldn't find much
Solution
As you have defined "I" as int, the range is - 2147483648 to 2647 Once - 2147483648 is reached (your code loop starts at 0 and increments by 1), the condition becomes false and the loop is interrupted
int i; System.out.println("Start: " + LocalTime.Now()); for (i = 0; i > -1; i++) { /*Infinite looP*/ } System.out.println("End :" + LocalTime.Now()); System.out.println("i :" + i);
Try the above and you will see that the final value is - 2147483648, so it comes out of the loop
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码