Android Utililty Methods Int Overflow Check

List of utility methods to do Int Overflow Check

Description

The list of methods to do Int Overflow Check are organized into topic(s).

Method

intaddAndCheck(int x, int y)
Add two integers, checking for overflow.
long s = (long) x + (long) y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
    throw new MathArithmeticException(
            LocalizedFormats.OVERFLOW_IN_ADDITION, x, y);
return (int) s;
intconstrain(int value, int min, int max)
constrain
if (value > max) {
    return max;
} else if (value < min) {
    return min;
} else {
    return value;
intmulAndCheck(int x, int y)
Multiply two integers, checking for overflow.
long m = ((long) x) * ((long) y);
if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) {
    throw new MathArithmeticException();
return (int) m;
longstirlingS2(final int n, final int k)
Returns the Stirling number of the second kind, " S(n,k) ", the number of ways of partitioning an n -element set into k non-empty subsets.
if (k < 0) {
    throw new NotPositiveException(k);
if (k > n) {
    throw new NumberIsTooLargeException(k, n, true);
long[][] stirlingS2 = STIRLING_S2.get();
if (stirlingS2 == null) {
...
intsubAndCheck(int x, int y)
Subtract two integers, checking for overflow.
long s = (long) x - (long) y;
if (s < Integer.MIN_VALUE || s > Integer.MAX_VALUE) {
    throw new MathArithmeticException(
            LocalizedFormats.OVERFLOW_IN_SUBTRACTION, x, y);
return (int) s;
intmultiply(int x, int y)
Multiply two fixed-point values.
long z = (long) x * (long) y;
return ((int) (z >> 16));
intmultiply(int x, int y)
Multiply two fixed-point values.
long z = (long) x * (long) y;
return ((int) (z >> 16));
intsqrt(int n)
Find the sqrt of a fixed-point value.
int s = (n + 65536) >> 1;
for (int i = 0; i < 8; i++) {
    s = (s + divide(n, s)) >> 1;
return s;
intdivide(int x, int y)
Divide two fixed-point values.
long z = (((long) x) << 32);
return (int) ((z / y) >> 16);