Java
Integer Underflow
Integer Overflow
Error Checking
Programming Tips

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

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

Java integer arithmetic uses fixed-width two's-complement values for byte, short, int, and long. When a calculation exceeds the representable range, Java does not raise an exception by default for the basic arithmetic operators; it wraps around.

That behavior is predictable, but it is also easy to miss in business logic, counters, pricing code, and ID generation. If overflow matters, you need to check for it explicitly.

What Overflow and Underflow Look Like

For int, the maximum value is 2147483647 and the minimum is -2147483648. Adding one to the maximum wraps to the minimum, and subtracting one from the minimum wraps to the maximum.

java
1public class WrapAroundDemo {
2    public static void main(String[] args) {
3        int max = Integer.MAX_VALUE;
4        int min = Integer.MIN_VALUE;
5
6        System.out.println(max + 1);
7        System.out.println(min - 1);
8    }
9}

Output:

text
-2147483648
2147483647

Java is not “detecting and fixing” the overflow here. It is simply discarding the bits that no longer fit.

Use Math.addExact and Friends When Overflow Is an Error

The standard library provides checked arithmetic helpers. They throw ArithmeticException when the result does not fit.

java
1public class ExactMathDemo {
2    public static void main(String[] args) {
3        try {
4            int result = Math.addExact(Integer.MAX_VALUE, 1);
5            System.out.println(result);
6        } catch (ArithmeticException ex) {
7            System.out.println("overflow detected");
8        }
9    }
10}

Related methods include Math.subtractExact, Math.multiplyExact, Math.incrementExact, Math.decrementExact, and Math.toIntExact.

These methods are the best default when overflow is logically invalid and you want the code to fail loudly.

Manual Checks Before the Operation

You can also check bounds before doing the arithmetic. That is useful when you want to return a fallback value or a custom error instead of throwing.

java
1public class ManualCheck {
2    static boolean willAddOverflow(int a, int b) {
3        if (b > 0) {
4            return a > Integer.MAX_VALUE - b;
5        }
6        if (b < 0) {
7            return a < Integer.MIN_VALUE - b;
8        }
9        return false;
10    }
11
12    public static void main(String[] args) {
13        int a = Integer.MAX_VALUE;
14        int b = 10;
15
16        if (willAddOverflow(a, b)) {
17            System.out.println("addition would overflow");
18        } else {
19            System.out.println(a + b);
20        }
21    }
22}

This approach keeps control in your code, but it is also easier to get wrong than Math.addExact if you repeat it everywhere.

Narrowing Conversions Need Separate Attention

Overflow does not only happen in arithmetic. It also happens when you cast from a wider type to a narrower one.

java
1public class CastDemo {
2    public static void main(String[] args) {
3        long large = 3_000_000_000L;
4        int narrowed = (int) large;
5        System.out.println(narrowed);
6    }
7}

The cast compiles, but the value is truncated. If that narrowing step matters, use Math.toIntExact instead of a plain cast.

When to Use BigInteger

If the domain allows values beyond long, then overflow checks are not enough. You need a different numeric type.

BigInteger stores arbitrarily large integers and is the right tool for cryptography, combinatorics, large counters, or any calculation where wraparound is unacceptable and range is unknown in advance.

It is slower and more verbose than primitive arithmetic, so use it when the requirements justify it.

Common Pitfalls

  • Assuming Java throws an exception automatically on primitive integer overflow. Normal +, -, and * do not.
  • Testing only positive overflow and forgetting negative underflow cases.
  • Replacing a checked operation with a cast that silently truncates the value.
  • Mixing int and long carelessly and assuming the wider result is always preserved through later assignments.
  • Using manual guard logic everywhere instead of centralizing the check or using Math.addExact style helpers.

Summary

  • Java primitive integer arithmetic wraps on overflow and underflow.
  • Use Math.addExact, subtractExact, and related methods when overflow should be treated as an error.
  • Manual pre-checks are possible, but they require careful boundary logic.
  • Narrowing casts can also lose data even when no arithmetic operator is involved.
  • Use BigInteger when valid values may exceed the primitive numeric range.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms