Math.abs(int) cannot represent the positive magnitude of Integer.MIN_VALUE, so that input remains negative.
Java Math.abs on Integer.MIN_VALUE: detect the one value that cannot turn positive
Validate before using magnitude
The int range contains one more negative value than positive values. A partition key or distance calculation that assumes Math.abs always returns nonnegative can produce an invalid index at this boundary. Java 15 adds Math.absExact, which throws instead of returning the wrapped result.
The fixture prints the surprising value, then rejects it with absExact. On older releases, widen to long before taking the absolute value. Checked arithmetic covers the same range principle for addition.
Do not repair an overflow afterward
Once an int result has wrapped, casting that result to long does not restore the lost positive magnitude. Widen the operand before the operation or use the exact method.
Working program
public class PartitionMagnitudeGate {
public static void main(String[] args) {
int partitionDelta = Integer.MIN_VALUE;
System.out.println(Math.abs(partitionDelta));
try { Math.absExact(partitionDelta); }
catch (ArithmeticException rejected) { System.out.println("magnitude overflow rejected"); }
System.out.println(Math.abs((long) partitionDelta));
}
}Output
-2147483648
magnitude overflow rejected
2147483648Cost and ownership
Each calculation uses constant time and storage. The failure is a representation limit, not a performance issue. Choose a wider result type when the full mathematical magnitude is required.
Common Mistakes
- Do not assume Math.abs(int) is always nonnegative.
- Do not cast the already-wrapped int result to long.
- Do not call Math.absExact from a Java 8 compilation target.
Read next
Java checked integer arithmetic: reject overflow before updating state, Java operators and numeric promotion, biginteger exact conversion, floor div mod negative.
