MathAbsoluteNegative
Math.abs does not always give a non-negative result. Please consider other methods for positive numbers.

Severity
WARNING

Alternate names: MathAbsoluteRandom

The problem

Math.abs returns a negative number when called with the largest negative number.

Example:

int veryNegative = Math.abs(Integer.MIN_VALUE);
long veryNegativeLong = Math.abs(Long.MIN_VALUE);

When trying to generate positive random numbers or fingerprints by using Math.abs around a random positive-or-negative integer (or long), there will a rare edge case where the returned value will be negative.

This is because there is no positive integer with the same magnitude as Integer.MIN_VALUE, which is equal to -Integer.MAX_VALUE - 1. Floating point numbers don’t suffer from this problem, as the sign is stored in a separate bit.

Instead, one should use random number generation functions that are guaranteed to generate positive numbers:

Random r = new Random();
int positiveNumber = r.nextInt(Integer.MAX_VALUE);

or map negative numbers onto the non-negative range:

long lng = r.nextLong();
lng = (lng == Long.MIN_VALUE) ? 0 : Math.abs(lng);

Suppression

Suppress false positives by adding the suppression annotation @SuppressWarnings("MathAbsoluteNegative") to the enclosing element.