Fundamentals 4 min read

How to Detect Integer Overflow in Java with Built‑in Math Methods

This article explains how to use Java's Math class methods such as addExact, subtractExact, and multiplyExact to detect integer overflow, provides the source code for each operation, discusses differences between int and long handling, and offers tips for performance‑aware usage.

Programmer DD
Programmer DD
Programmer DD
How to Detect Integer Overflow in Java with Built‑in Math Methods

# Problem

When solving practice problems, you may need to determine whether adding two int values overflows and, if so, return Integer.MAX_VALUE.

# Solution

JDK 8 already implements overflow‑checking methods in Math; the following examples were found on StackOverflow.

Addition

public static int addExact(int x, int y) {
    int r = x + y;
    // HD 2-12 Overflow iff both arguments have the opposite sign of the result
    if (((x ^ r) & (y ^ r)) < 0) {
        throw new ArithmeticException("integer overflow");
    }
    return r;
}

Subtraction

public static int subtractExact(int x, int y) {
    int r = x - y;
    // HD 2-12 Overflow iff the arguments have different signs and the sign of the result is different than the sign of x
    if (((x ^ y) & (x ^ r)) < 0) {
        throw new ArithmeticException("integer overflow");
    }
    return r;
}

Multiplication (int)

public static int multiplyExact(int x, int y) {
    long r = (long) x * (long) y;
    if ((int) r != r) {
        throw new ArithmeticException("integer overflow");
    }
    return (int) r;
}

Note that long and int behave differently; an overload for long multiplication is also provided.

Multiplication (long)

public static long multiplyExact(long x, long y) {
    long r = x * y;
    long ax = Math.abs(x);
    long ay = Math.abs(y);
    if (((ax | ay) >>> 31) != 0) {
        // Some bits greater than 2^31 that might cause overflow
        // Check the result using division and handle the special case Long.MIN_VALUE * -1
        if ((y != 0 && r / y != x) || (x == Long.MIN_VALUE && y == -1)) {
            throw new ArithmeticException("long overflow");
        }
    }
    return r;
}

Directly calling these methods is the most convenient approach, but for performance‑critical code you may want to avoid the relatively expensive exception handling.

The purpose of this note is to summarize the built‑in overflow‑checking functions that Java already provides, making it easier to share with others.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javaprogramming fundamentalsinteger overflowMath.addExact
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.