roamarox roamarox - 23 days ago 6
Java Question

Why does the loop iterate beyond Integer.MAX_VALUE?

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

i = Integer.MAX_VALUE + 1
but it seems to deny the limit. Why does this happen?

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


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: