roamarox roamarox - 1 year ago 67
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++);

Answer Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download