Versions Compared

Key

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

Programs must not allow mathematical operations to exceed the integer ranges provided by their primitive integer data types. According to The Java Language Specification (JLS), §4.2.2, "Integer Operations" [JLS 20052015]:

The built-in integer operators do not indicate overflow or underflow in any way. Integer operators can throw a NullPointerException if unboxing conversion of a null reference is required. Other than that, the only integer operators that can throw an exception are the integer divide operator / and the integer remainder operator %, which throw an ArithmeticException if the right-hand operand is zero, and the increment and decrement operators ++ and -- which can throw an OutOfMemoryError if boxing conversion is required and there is insufficient memory to perform the conversion.

The integral types in Java, representation, and inclusive ranges are shown in the following table taken from the JLS, §4.2.1, "Integral Types and Values" [JLS 20052015]:

Type

Representation

Inclusive Range

byte

8-bit signed two's-complement

−128 to 127

short

16-bit signed two's-complement

−32,768 to 32,767

int

32-bit signed two's-complement

−2,147,483,648 to 2,147,483,647

long

64-bit signed two's-complement

−9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

char

16-bit unsigned integers representing UTF-16 code units

\u0000 to \uffff (0 to 65,535)

The following table shows the integer overflow behavior of the integral operators.

Operator

Overflow

 


Operator

Overflow

 


Operator

Overflow

 


Operator

Overflow

+

Yes

 


-=

Yes

 


<<

No

 


<

No

-

Yes

 


*=

Yes

 


>>

No

 


>

No

*

Yes

 


/=

Yes

 


&

No

 


>=

No

/

Yes

 


%=

No

 


\

No

 


<=

No

%

No

 


<<=

No

 


^

No

 


==

No

++

Yes

 


>>=

No

 


~

No

 


!=

No

--

Yes

 


&=

No

 


!

No

=

No

 


|=

No

 


Unary +

No

+=

Yes

 


^=

No

 


Unary -

Yes

Because the ranges of Java types are not symmetric (the negation of each minimum value is one more than each maximum value), even operations such as unary negation can overflow if applied to a minimum value. Because the java.lang.math.abs() method returns the absolute value of any number, it can also overflow if given the minimum int or long as an argument.

...

The following code example shows the necessary precondition checks required for each arithmetic operation on arguments of type int. The checks for the other integral types are analogous. These methods throw an exception when an integer overflow would otherwise occur; any other conforming error handling is also acceptable. Since ArithmeticException inherits from RuntimeException, we do not need to declare it in a throws clause.

Code Block
Code Block
bgColor#ccccff
static final int safeAdd(int left, int right)
                 throws ArithmeticException {
  if (right > 0 ? left > Integer.MAX_VALUE - right
                : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left + right;
}

static final int safeSubtract(int left, int right) 
                 throws ArithmeticException {
  if (right > 0 ? left < Integer.MIN_VALUE + right 
                : left > Integer.MAX_VALUE + right) {
    throw new ArithmeticException("Integer overflow");
  }
  return left - right;
}

static final int safeMultiply(int left, int right) {
  if               throws ArithmeticException {
  if (right (right > 0 ? left > Integer.MAX_VALUE/right
                  || left < Integer.MIN_VALUE/right 
                : (right < -1 ? left > Integer.MIN_VALUE/right 
                                || left < Integer.MAX_VALUE/right
                              : right == -1 
                                && left == Integer.MIN_VALUE) ) {
    throw new ArithmeticException("Integer overflow");
  }
  return left * right;
}

static final int safeDivide(int left, int right)
                 throws ArithmeticException {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
  return left / right;
}

static final int safeNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return -a;
}
static final int safeAbs(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
  return Math.abs(a);
}

...

This compliant solution uses the safeAdd() and safeMultiply() methods defined in the "Precondition Testing" section to perform secure integral operations or throw ArithmeticException on overflow.:

Code Block
bgColor#ccccff
public static int multAccum(int oldAcc, int newVal, int scale) {
                  throws ArithmeticException {
  return safeAdd(return safeAdd(oldAcc, safeMultiply(newVal, scale));
}

...

Code Block
bgColor#ccccff
public static int multAccum(int oldAcc, int newVal, int scale)
                  throws ArithmeticException {
  return Math.addExact(oldAcc, Math.multiplyExact(newVal, scale));
}

...

Code Block
bgColor#ccccff
public static long intRangeCheck(long value) {
  if ((value < Integer.MIN_VALUE) ||             throws ArithmeticException {
  if ((value < Integer.MIN_VALUE) || (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 downcast
}

...

This compliant solution uses the BigInteger technique to detect overflow.:

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(); // Safe conversion
}

...

The two arguments to the compareAndSet() method are the expected value of the variable when the method is invoked and the intended new value. The variable's value is updated only when the current value and the expected value are equal [API 2006] (refer to VNA02-J. Ensure that compound operations on shared variables are atomic for more details).

Exceptions

NUM00-J-EX0: Depending on circumstances, integer overflow could be benign. For example, many algorithms for computing hash codes use modular arithmetic, intentionally allowing overflow to occur. Such benign uses must be carefully documented.

NUM00-J-EX1: Prevention of integer overflow is unnecessary for numeric fields that undergo bitwise operations and not arithmetic operations (see NUM01-J. Do not perform bitwise and arithmetic operations on the same data for more information).

...

Failure to perform appropriate range checking can lead to integer overflows, which can cause unexpected program control flow or unanticipated program behavior.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

NUM00-J

Medium

Unlikely

Medium

P4

L3

Automated Detection

Automated detection of integer operations that can potentially overflow is straightforward. Automatic determination of which potential overflows are true errors and which are intended by the programmer is infeasible. Heuristic warnings might be helpful.

Tool
Version
Checker
Description
Coverity7.5

BAD_SHIFT
OVERFLOW_BEFORE_WIDEN

Implemented

Related Guidelines

Description
CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

JAVA.MATH.ABSRAND
JAVA.ARITH.OFLOW

Abs on random (Java)
Cast: int Computation to long (Java)

Coverity7.5

BAD_SHIFT
OVERFLOW_BEFORE_WIDEN

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.NUM00.ICO
CERT.NUM00.BSA
CERT.NUM00.CACO
Avoid calculations which result in overflow or NaN
Do not use an integer outside the range of [0, 31] as the amount of a shift
Avoid using compound assignment operators in cases which may cause overflow
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V5308, V6117

Related Guidelines

SEI CERT C

The CERT C Secure

Coding Standard

INT32-C. Ensure that operations on signed integers do not result in overflow

ISO/IEC TR 24772:2010

Wrap-around Error [XYY]

MITRE CWE

CWE-682, Incorrect Calculation
CWE-190, Integer Overflow or Wraparound
CWE-191, Integer Underflow (Wrap or Wraparound)

Android Implementation Details

...

to calculate the available memory in an SD card, which could result in a negative value when the available memory is larger than Integer.MAX_VALUE. Note that these methods are deprecated in API level 18 and replaced by getAvailableBlocksLong() and getBlockSizeLong().

Bibliography

...


...