How does Java handle integer underflows and overflows and how would you check for it?

integer, integer-overflow, java

Solution

If it overflows, it goes back to the minimum value and continues from there. If it underflows, it goes back to the maximum value and continues from there.

You can make use of the `Math#addExact()` and `Math#subtractExact()` methods which will throw an `ArithmeticException` on overflow.

public static boolean willAdditionOverflow(int left, int right) {
    try {
        Math.addExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

public static boolean willSubtractionOverflow(int left, int right) {
    try {
        Math.subtractExact(left, right);
        return false;
    } catch (ArithmeticException e) {
        return true;
    }
}

You can substitute `int` by `long` to perform the same checks for `long`.

The source code can be found here and here respectively.

Of course, you could also just use them right away instead of hiding them in a `boolean` utility method.

If you think that this may occur more than often, then consider using a datatype or object which can store larger values, e.g. `long` or maybe `java.math.BigInteger`. The last one doesn't overflow, practically, the available JVM memory is the limit.

Problem

How does Java handle integer underflows and overflows? Leading on from that, how would you check/test that this is occurring?

Original source

Related problems