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.
Code
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
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.