Special behavior of for loop in Java
•
Java
Today, while reading boxing and automatic boxing, I came up with a scene and found that I was trapped in an infinite cycle
I checked my code twice, but I didn't find any errors If someone can see and advise me where I did wrong, I will have this infinite cycle
Please find the code below
public class InTheLoop {
public static final int END = Integer.MAX_VALUE;
public static final int START = END - 100;
public static void main(String[] args) {
int count = 0;
//Infinite loop starts.
for (int i = START; i <= END; i++) {
count++;
System.out.println(count);
}
// This never got printed.
System.out.println("hi I am out of for loop" +count);
}
}
Solution
Note that your end is equal to the maximum possible value that an integer can hold (the value is 2147483647) This means that I < = end is always true for any value I may hold When I actually reach 2147483647, it is still < = end In the next iteration, you try to increment it by 1, which will cause overflow, and I change to - 2147483648, which is still < = end, and the loop will continue forever
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
二维码
