Wednesday, February 29, 2012

Integer overflow in Java

What would happen in Java when you increment an Integer variable that already contains its maximum value?

No, Java would not throw any exception :(

Lets write a simple program to test it:

    
public static void main(String[] args) {
   int i = Integer.MAX_VALUE;
   System.out.println("Before: " + i 
             + " = " + Integer.toBinaryString(i));

   i++;
   System.out.println("After: " + i 
             + " = " + Integer.toBinaryString(i));        
}

The output is:

Before: 2147483647 = 01111111111111111111111111111111
After: -2147483648 = 10000000000000000000000000000000

As you see, it is negative.

So, when you increment Integer.MAX_VALUE by 1 it becomes Integer.MIN_VALUE.

No comments:

Post a Comment