Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
public static long intRangeCheck(long value)
                   throws ArithmeticException {
  if ((value < Integer.MIN_VALUE) || (value > Integer.MAX_VALUE)) {
    throw new ArithmeticException("Integer overflow");
  }
  return value;
}

public static int multAccum(int oldAcc, int newVal, int scale)
                  throws ArithmeticException {
  final long res = intRangeCheck(
   ((long) oldAcc) + intRangeCheck((long) newVal * (long) scale)
  );
  return (int) res; // Safe down-castdowncast
}

Note that this approach cannot be applied to values of type long because long is the largest primitive integral type. Use the BigInteger technique instead when the original variables are of type long.

...

Code Block
bgColor#ccccff
private static final BigInteger bigMaxInt = 
  BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger bigMinInt =    
  BigInteger.valueOf(Integer.MIN_VALUE);

public static BigInteger intRangeCheck(BigInteger val)
                         throws ArithmeticException {
  if (val.compareTo(bigMaxInt) == 1 ||
      val.compareTo(bigMinInt) == -1) {
    throw new ArithmeticException("Integer overflow");
  }
  return val;
}

public static int multAccum(int oldAcc, int newVal, int scale)
                            throws ArithmeticException {
  BigInteger product =
    BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
  BigInteger res = 
    intRangeCheck(BigInteger.valueOf(oldAcc).add(product));
  return res.intValue(); // safeSafe conversion
}

Noncompliant Code Example (AtomicInteger)

...

[API 2006]

Class AtomicInteger

[Bloch 2005]

Puzzle 27, "Shifty i's"

[Bloch 2008]Item 12, "Minimize the Accessibility of Classes and Members"

[JLS 2005]

§4.2.2, "Integer Operations"
§15.22, "Bitwise and Logical Operators"

[Seacord 2005]

Chapter 5, "Integers"

[Seacord 2015]Image result for video icon IDS17-J. Prevent XML External Entity Attacks LiveLesson

[Tutorials 2008]

"Primitive Data Types"

 

...