Math Abs Integer Min Overflow

Math.abs(Integer.MIN_VALUE) does not throw: the documented contract returns the same negative value, so widen to long or guard the boundary before negating.

JavaData Integrity

Code

snippet
public class AbsEdge {

    public static void main(String[] args) {
        int min = Integer.MIN_VALUE;

        // 普通值:abs 正常取正
        System.out.println("abs(-5): " + Math.abs(-5));

        // 文档契约:abs(Integer.MIN_VALUE) 不抛 overflow,原样返回最小值(仍为负)
        System.out.println("abs(MIN_VALUE): " + Math.abs(min));

        // 先扩宽到 long 再取 abs,就没有这个边界问题
        System.out.println("absLong: " + Math.abs((long) min));

        // 安全取负:显式边界判断(或用 negateExact 让溢出当场抛出)
        System.out.println("safe: " + (min == Integer.MIN_VALUE ? 2147483648L : Math.abs(min)));
    }
}

How it works

Structurally, expect the class AbsEdge and the function main and nothing else.

Points of care

  • Its one and only prerequisite is the language toolchain.

Applying it

The main signature, verbatim, is public static void main(String[] args)

The run emits 4 labeled sections — abs(-5):, abs(MIN_VALUE):, absLong:, safe: — one per step.

Statements that matter

int min = Integer.MIN_VALUE;

Interactive Tools for This Topic

FAQ

What does Math Abs Integer Min Overflow print when run?
Invoke the file as-is — the `abs(-5):`, `abs(MIN_VALUE):`, `absLong:` prefixes identify which step printed each line.