ArithmeticUtils { public static int addAndCheck(int x, int y) throws MathArithmeticException { long s = (long)x + (long)y; if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) { throw new MathArithmeticException(LocalizedFormats.OVERFLOW_IN_ADDITION, x, y); } return (int)s; } private  ArithmeticUtils(); static int addAndCheck(int x, int y); static long addAndCheck(long a, long b); @Deprecated static long binomialCoefficient(final int n, final int k); @Deprecated static double binomialCoefficientDouble(final int n, final int k); @Deprecated static double binomialCoefficientLog(final int n, final int k); @Deprecated static long factorial(final int n); @Deprecated static double factorialDouble(final int n); @Deprecated static double factorialLog(final int n); static int gcd(int p, int q); static long gcd(final long p, final long q); static int lcm(int a, int b); static long lcm(long a, long b); static int mulAndCheck(int x, int y); static long mulAndCheck(long a, long b); static int subAndCheck(int x, int y); static long subAndCheck(long a, long b); static int pow(final int k,
                          final int e); @Deprecated static int pow(final int k, long e); static long pow(final long k,
                           final int e); @Deprecated static long pow(final long k, long e); static BigInteger pow(final BigInteger k, int e); static BigInteger pow(final BigInteger k, long e); static BigInteger pow(final BigInteger k, BigInteger e); @Deprecated static long stirlingS2(final int n, final int k); static boolean isPowerOfTwo(long n);  }
@Test public void testAddAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; Assert.assertEquals(big, ArithmeticUtils.addAndCheck(big, 0)); try { ArithmeticUtils.addAndCheck(big, 1); Assert.fail("Expecting MathArithmeticException"); } catch (MathArithmeticException ex) { } try { ArithmeticUtils.addAndCheck(bigNeg, -1); Assert.fail("Expecting MathArithmeticException"); } catch (MathArithmeticException ex) { } }
@Test public void testAddAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; Assert.assertEquals(max, ArithmeticUtils.addAndCheck(max, 0L)); Assert.assertEquals(min, ArithmeticUtils.addAndCheck(min, 0L)); Assert.assertEquals(max, ArithmeticUtils.addAndCheck(0L, max)); Assert.assertEquals(min, ArithmeticUtils.addAndCheck(0L, min)); Assert.assertEquals(1, ArithmeticUtils.addAndCheck(-1L, 2L)); Assert.assertEquals(1, ArithmeticUtils.addAndCheck(2L, -1L)); Assert.assertEquals(-3, ArithmeticUtils.addAndCheck(-2L, -1L)); Assert.assertEquals(min, ArithmeticUtils.addAndCheck(min + 1, -1L)); Assert.assertEquals(-1, ArithmeticUtils.addAndCheck(min, max)); testAddAndCheckLongFailure(max, 1L); testAddAndCheckLongFailure(min, -1L); testAddAndCheckLongFailure(1L, max); testAddAndCheckLongFailure(-1L, min); testAddAndCheckLongFailure(max, max); testAddAndCheckLongFailure(min, min); }