roamarox roamarox - 2 months ago 8
Java Question

Java Weird loopy behaviour

Can someone explain why this code is an infinite loop on Java 7,8?

public static void main(String[] args) {
for (int i = Integer.MAX_VALUE - 100; i <= Integer.MAX_VALUE; i++);
}

Answer

Look at

 i <= Integer.MAX_VALUE

This is always true. If i = Integer.MAX_VALUE+1 then it will overflow, and become negative.

Do this:

 System.println(Integer.MAX_VALUE+1)
Comments