Search code examples
javainteger-overflowarithmeticexception

ArithmeticException not thrown for overflow within 2^32


I know assigning a number greater than 2^32 has a chance to generate an ArithmeticException but today while I was programming:

int x = 65535
System.out.println(x * x);

Output: -131071

So no exception but an unexpected result.


Solution

  • Overflow

    Multiplication is not protected against overflows.

    What you see here is integer overflow. If you take the biggest integer Integer.MAX_VALUE and add 1 you get the smallest integer INTEGER.MIN_VALUE:

    int value = Integer.MAX_VALUE;
    System.out.println(value);  // 2147483647
    value++;
    System.out.println(value);  // -2147483648
    

    The same happens here because

    65_535 * 65_535 = 4_294_836_225 > 2_147_483_647
    

    Range of int

    In Java int is a signed-32-bit value. In particular, it is not unsigned.

                     |    min-value   |   max-value   |
    -----------------|----------------|---------------|
       signed-32-bit |          -2^31 |      2^31 - 1 |
                     | -2_147_483_648 | 2_147_483_647 |
    -----------------|----------------|---------------|
     unsigned-32-bit |        2^0 - 1 |      2^32 - 1 |
                     |              0 | 4_294_967_295 |
    

    Exception

    A multiplication does not throw an ArithmeticException. To my knowledge this only happens if you divide by 0, since this should not be possible by definition. Also see the documentation of the exception.

    For a protected multiplication consider using Math#multiplyExact (documentation).