Why Math.abs(Integer.MIN_VALUE) Returns a Negative Value in Java
The article explains that Math.abs() can return a negative result when applied to Integer.MIN_VALUE because the absolute value exceeds the int range, detailing the two's‑complement representation, overflow behavior, and how the JLS defines the operation.
Problem Overview
When calling Math.abs() on an int value, developers may encounter a surprising negative result. This occurs specifically when the argument is Integer.MIN_VALUE (‑2147483648), because the absolute value cannot be represented within the 32‑bit signed integer range.
Demonstration Code
public static void main(String[] args) {
int min = Integer.MIN_VALUE;
int max = Integer.MAX_VALUE;
System.out.println("Min: " + min);
System.out.println("Max: " + max);
int abs = Math.abs(min);
System.out.println("Abs of Min: " + abs);
}Running this program prints:
Min: -2147483648
Max: 2147483647
Abs of Min: -2147483648Why the Negative Result Occurs
The source of the bug lies in the two's‑complement representation of signed integers. In Java, -x is defined as (~x) + 1 (JLS §15.15.4). For Integer.MIN_VALUE the binary pattern is 1000…000 (sign bit 1, all other bits 0). Flipping the bits yields 0111…111 (2147483647), then adding 1 wraps around to 1000…000 again, which is still -2147483648. Because the positive counterpart (2147483648) exceeds Integer.MAX_VALUE, the operation overflows and the original negative value is returned.
Implications
The same issue exists for long values with Long.MIN_VALUE. Developers must guard against this edge case, for example by converting to a larger type (e.g., long) before taking the absolute value, or by handling MIN_VALUE explicitly.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
