MathUtil { public static int sum(int ...data){ int result = 0; for(int item : data){ if(item > 0){ if(result > Integer.MAX_VALUE - item){ throw new IllegalArgumentException("sum bigger than max int"); } } if(item < 0){ if(result < Integer.MIN_VALUE - item){ throw new IllegalArgumentException("sum smaller than max int"); } } result += item; } return result; }  static int sum(int ...data);  }
@Test public void testSum() { Assert.assertEquals(Integer.MAX_VALUE, MathUtil.sum(Integer.MAX_VALUE, 0, 0)); Assert.assertEquals(Integer.MAX_VALUE, MathUtil.sum(Integer.MAX_VALUE - 1, 1, 0)); try { MathUtil.sum(Integer.MAX_VALUE, 1); Assert.fail(); } catch (IllegalArgumentException e) { } Assert.assertEquals(Integer.MIN_VALUE, MathUtil.sum(Integer.MIN_VALUE, 0, 0)); Assert.assertEquals(Integer.MIN_VALUE, MathUtil.sum(Integer.MIN_VALUE + 1, -1, 0)); try { MathUtil.sum(Integer.MIN_VALUE, -1); Assert.fail(); } catch (IllegalArgumentException e) { } }