Versions Compared

Key

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

...

Type

Representation

Inclusive Range

byte

8-bit signed two's-complement

-128 −128 to 127

short

16-bit signed two's-complement

-32−32,768 to 32,767

int

32-bit signed two's-complement

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

long

64-bit signed two's-complement

-9−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)

...

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

 

Operator

Overflow

+

yesYes

 

-=

yesYes

 

<<

noNo

 

<

noNo

-

yesYes

 

*=

yesYes

 

>>

noNo

 

>

noNo

*

yesYes

 

/=

yesYes

 

&

noNo

 

>=

noNo

/

yesYes

 

%=

noNo

 

\

noNo

 

<=

noNo

%

noNo

 

<<=

noNo

 

^

noNo

 

==

noNo

++

yesYes

 

>>=

noNo

 

~

noNo

 

!=

noNo

--

yesYes

 

&=

noNo

 

!

noNo

=

noNo

 

|=

noNo

 

unary Unary +

noNo

+=

yesYes

 

^=

noNo

 

unary Unary -

yesYes

Because the ranges of Java types are not symmetric (the negation of each minimum value is one more than each maximum value), even operations like 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.

When a mathematical operation cannot be represented using the supplied integer types, Java's built-in integer operators silently wrap the result without indicating overflow. This The silent wrap can result in incorrect computations and unanticipated outcomes. Failure to account for integer overflow has resulted in failures of real systems, for example, when implementing the compareTo() method. The meaning of the return value of the compareTo() method is defined only in terms of its sign and whether it is zero; the magnitude of the return value is irrelevant. Consequently, an apparent but incorrect optimization would be to subtract the operands and return the result. For operands of opposite signs, this approach can result in integer overflow, consequently violating the compareTo() contract [Bloch 2008, Item 12].

...

The precondition testing technique requires different precondition tests for each arithmetic operation. This approach can be somewhat more difficult to implement and to audit than either of the other two approaches.

...

The following code example shows the necessary pre-condition 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.

...

These method calls are likely to be inlined by most just-in-time systems (JITsJIT) systems.

These checks can be simplified when the original type is char. Because the range of type char includes only positive values, all comparisons with negative values may be omitted.

...

This compliant solution uses the addExact() and multiplyExact() methods defined in the Math class. These methods were added to Java as part of the Java 8 release, and they also either return a mathematically correct value or throw ArithmeticException. The Math class also provides SubtractExact() and negateExact(), but does not provide any methods for safe division or absolute value.

...

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; // safeSafe down-cast
}

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.

...

Operations on objects of type AtomicInteger suffer from the same overflow issues as other integer types. The solutions are generally similar to the solutions already presented; however, concurrency issues add additional complications. First, potential issues with time-of-check, time-of-use (TOCTOU) must be avoided ; (see rule VNA02-J. Ensure that compound operations on shared variables are atomic for more information). Second, use of an AtomicInteger creates happens-before relationships between the various threads that access it. Consequently, changes to the number of accesses or order of accesses can alter the execution of the overall program. In such cases, you must either choose to accept the altered execution or carefully craft your implementation to preserve the exact number of accesses and order of accesses to the AtomicInteger.

...

Code Block
bgColor#ccccff
class InventoryManager {
  private final AtomicInteger itemsInInventory =
      new AtomicInteger(100);

  public final void nextItem() {
    while (true) {
      int old = itemsInInventory.get();
      if (old == Integer.MAX_VALUE) {
        throw new ArithmeticException("Integer overflow");
      }
      int next = old + 1; // Increment
      if (itemsInInventory.compareAndSet(old, next)) {
        break;
      }
    } // endEnd while
  } // endEnd nextItem()
}

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 (refer to rule VNA02-J. Ensure that compound operations on shared variables are atomic for more details).

Exceptions

NUM00-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-EX1: Prevention of integer overflow is unnecessary for numeric fields that undergo bitwise operations and not arithmetic operations . See (see rule NUM01-J. Do not perform bitwise and arithmetic operations on the same data for more information).

Risk Assessment

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

mediumMedium

unlikelyUnlikely

mediumMedium

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

Android Implementation Details

Mezzofanti for Android contained an integer overflow which that prevented the use of a big SD card. Mezzofanti contained an expression:

...

to calculate the available memory in an SD card, which could result in a negative value when the available memory is bigger larger than Integer.MAX_VALUE.

Note these methods are deprecated in API level 18 and replaced by getAvailableBlocksLong() and getBlockSizeLong().

...

 

...