Close

Java 8 - Numeric overflow safe code by using Math class xyzExact() methods

[Updated: Apr 28, 2017, Created: Apr 28, 2017]

Java arithmetic operations will silently cause numeric overflow if the result is bigger than the target data type capacity. For example:

public class OverflowExample1 {

  public static void main(String[] args) {
      int i = 2000000000;
      int j = 1000000000;

      int out = i + j;
      System.out.println(out);
  }
}

Output

-1294967296

Java 8 introduce various methods in the java.lang.Math class which will throw ArithmeticException instead of silently allowing numeric overflow. Following example uses int Math#addExact(int a, int b)

public class OverflowExample2 {

  public static void main(String[] args) {
      int i = 2000000000;
      int j = 1000000000;

      int out = Math.addExact(i, j);
      System.out.println(out);
  }
}

Output

Caused by: java.lang.ArithmeticException: integer overflow
at java.lang.Math.addExact(Math.java:790)
at com.logicbig.example.OverflowExample2.main(OverflowExample2.java:9)
... 6 more

We can catch this exception and inform the user. Or we can take an alternative action on numeric overflow:

public class OverflowExample3 {

  public static void main(String[] args) {
      int i = 2000000000;
      int j = 1000000000;

      try {
          int out = Math.addExact(i, j);
          System.out.println(out);
      }catch (ArithmeticException e){
          BigInteger b1 = BigInteger.valueOf(i);
          BigInteger b2 = BigInteger.valueOf(j);
          BigInteger output = b1.add(b2);
          System.out.println(output);
      }
  }
}

Output

3000000000

Followings are the other similar public static methods in java.lang.Math class:

int addExact(int x, int y)
long addExact(long x, long y)
int subtractExact(int x, int y)
long subtractExact(long x, long y)
int multiplyExact(int x, int y)
long multiplyExact(long x, long y)
int incrementExact(int a)
long incrementExact(long a)
int decrementExact(int a)
long decrementExact(long a)
int negateExact(int a)
long negateExact(long a)
int toIntExact(long value)

Example Project

Dependencies and Technologies Used:

  • JDK 1.8
  • Maven 3.3.9

Exact Operations Select All Download
  • math-exact-operation-examples
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also