Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to detect integer overflow

Short answer

Ordinary operations silently wrap the result around the limit. The Math.addExact(), multiplyExact() and similar methods throw an exception instead:

void main() {
    int max = Integer.MAX_VALUE;
 
    IO.println(max + 1);
    IO.println(Math.addExact(max, 1));
}

Output:

-2147483648
Exception in thread "main" java.lang.ArithmeticException: integer overflow

Catching overflow

Catch ArithmeticException to handle the situation:

void main() {
    int items = 70_000;
    int price = 40_000;
    try {
        IO.println(Math.multiplyExact(items, price));
    } catch (ArithmeticException e) {
        IO.println("Too large: " + e.getMessage());
    }
}

Output:

Too large: integer overflow

Calculating in long

Often it is enough to do the calculation in long. Cast at least one operand to long before multiplying:

void main() {
    int items = 70_000;
    int price = 40_000;
 
    long total = (long) items * price;
    IO.println(total);
}

Output:

2800000000

Common mistake

Casting the result to long. The multiplication was done in int and overflowed before the value got into the long:

void main() {
    int items = 70_000;
    int price = 40_000;
 
    long wrong = (long) (items * price);
    IO.println(wrong);
}

Output:

-1494967296

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.