Silent number overflows in Java


What's inside this article ⌄
  • Java math exact methods overflow
  • AddExact vs regular addition Java
  • Integer overflow Java
  • Java safe arithmetic operations

Consider this example:

int result = Integer.MAX_VALUE + 1;
// Results in Integer.MIN_VALUE due to overflow

In regular arithmetic operations, when an overflow occurs, Java silently wraps around, which leads to bugs that are hard to detect.


Java’s Exact Methods

Safe Addition

Math.addExact() performs addition and throws an ArithmeticException if the result would overflow. It’s available for both int and long types:

try {
    int result = Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
    System.out.println("Addition would cause overflow!");
}

Safe Multiplication

Similar to addExact, multiplyExact handles multiplication operations safely:

try {
    int result = Math.multiplyExact(100000, 100000);
} catch (ArithmeticException e) {
    System.out.println("Multiplication would cause overflow!");
}

There is a one for longs as well.

Safe Subtraction

subtractExact ensures safe subtraction operations:

try {
   int result = Math.subtractExact(Integer.MIN_VALUE, 1);
} catch (ArithmeticException e) {
   System.out.println("Subtraction would cause overflow!");
}

Other Exact Arithmetic Methods

Java also provides several other exact arithmetic methods:

incrementExact – increments by one, throws ArithmeticException:

int result = Math.incrementExact(Integer.MAX_VALUE);

decrementExact – decrements by one, throws ArithmeticException:

int result = Math.decrementExact(Integer.MIN_VALUE);

negateExact – returns the negation of the argument, throws ArithmeticException:

int result = Math.negateExact(Integer.MIN_VALUE);

toIntExact – returns the value of the long argument, throws ArithmeticException:

int result = Math.toIntExact(Long.MAX_VALUE);

Applications

These methods are particularly useful in:

  1. Financial calculations where accuracy is crucial
  2. Scientific computations that cannot tolerate overflow
  3. Safety-critical applications
  4. Input validation scenarios

Best Practices

  1. Use exact methods when dealing with untrusted input
  2. Implement proper exception handling when using these methods
  3. Consider using BigInteger or BigDecimal for huge numbers

Example Usage Pattern

Here’s a practical example combining several exact methods:

public class SafeCalculator {
   public static int calculateTotal(int quantity, int price) {
      try {
         // First multiply quantity and price
         int subtotal = Math.multiplyExact(quantity, price);
         // Add tax (assuming 10%)
         int tax = Math.multiplyExact(subtotal, 10);
         tax = Math.divideExact(tax, 100);
         // Return total with tax
         return Math.addExact(subtotal, tax);
      } catch (ArithmeticException e) {
        throw new IllegalArgumentException("Calculation would cause overflow", e);
      }
   }
}