Wednesday, May 14, 2008

Index overflow in Java for loop

The following little code snippet shows the overflow of for loop index in Java.

public class Out {
public static void main(String[] ars) {
for(int i = 0; i <= 2147483647 ; i+=100000000 )
{
System.out.println( i + "\n" );
}
}
}

You may expect that the iteration count is 22. But it is not true. i is 2100000000 after the 22nd iteration. Then 100000000 is added to i(2100000000) again. 2200000000 is bigger than 2147483647. So int overflow will happen. i will become a negative integer. So the loop will continue.

For details of loop index overflow, you can refer to Programming Language Pragmatics.

No comments: