TIL: Math.abs in Java is not always non-negative

🚀 posted 2022-12-02
#️⃣ [ #tech   #til   #java ]

The function Math.abs(int) defined as

Returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.

is supposed to give you the absolute number of your given input. Which should be always non-negative.

But it turns out that this is not always the case:

Note that if the argument is equal to the value of Integer.MIN_VALUE, the most negative representable int value, the result is that same value, which is negative.

The result of Math.abs(Integer.MIN_VALUE) is Integer.MIN_VALUE. This is because of the implementation:

return (a < 0) ? -a : a;

The negation of Integer.MIN_VALUE is 2^32 = 4,294,967,296 and since 2^32 - 1 = 4_294_967_296 is the biggest possible Integer in Java it comes to an integer overflow.

That was it.
Bye 👋🏼