Search code examples
javamathinteger-overflow

java arithmetic


why this code returns wrong value?

int i=Integer.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);

Solution

  • When you add 1 to Integer.MAX_VALUE it overflows and wraps around to Integer.MIN_VALUE.

    This happens because Java uses two's complement to represent integers. An example in 4 bits:

    0000 : 0
    0001 : 1
    ...
    0111 : 7 (max value)
    1000 : -8 (min value)
    ...
    1110 : -2
    1111 : -1
    

    So when you add 1 to 0111 (max) it goes to 1000, and that's the minimum. Expand this idea to 32-bits and it works the same way.


    As for why your long is also showing an incorrect result, it's because it's performing addition on int s and then implicitly converting to long. You need to do:

    long l = (long) Integer.MAX_VALUE + 1
    System.out.println(l); // now prints the correct value