Integer Overflow

The loop : Inside Out

Have a look at below code and guess what could be the output.

public class Puzzle26 
{
public static final int END=Integer.MAX_VALUE;
public static final int START=END-100;
public static void main(String args[])
{
int count = 0;
for(int i=START;i<=END;i++)
count++;
System.out.println(count);
}
}


At a first glance you might think this will print 100, off course because, END is 100 more than START. But look more carefully we are using less than equal to sign. So now you might guess it will print 101. Well, no. This program does not print a thing. 

The reason is every integer is less than or equal to Integer.MAX_VALUE. And the moment our program increases Integer.MAX_VALUE there cannot be any value greater than that so it increments the variable i to -2147483648, which is the lowest integer value and then keeps incrementing it to 2147483647 i.e. the largest integer value and so on, and it goes to an infinite loop.

So whenever you are playing with integral type, be aware of the boundary conditions. What happens if the value overflows or underflows ?

Comments

Popular posts from this blog

Integer.MAX_VALUE, Double.POSITIVE_INFINITY and Double.NaN in Java