Versions Compared

Key

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

...

The three main techniques for detecting unintended integer overflow are:

  • Pre-condition testing of the inputs. Check the inputs to each arithmetic operator to ensure that overflow cannot occur. Throw an ArithmeticException when the operation would overflow if it were performed, otherwise perform the operation. We call this technique "Pre-condition the inputs" hereafter, for convenience.
  • Use a larger type and downcast. Cast the inputs to the next larger primitive integer type and perform the arithmetic in the larger size. Check each intermediate result for overflow of the original smaller type; throw an ArithmeticException if the range check fails. Note that the range check must be performed after each arithmetic operation. Downcast the final result to the original smaller type before assigning to the result variable. This approach cannot be use for type long, because long is already the largest primitive integer type.
  • Use BigInteger. Convert the inputs into objects of type BigInteger and perform all arithmetic using BigInteger methods. Throw an ArithmeticException if the final result is outside the range of the original smaller type, otherwise convert back to the intended result type.

...