Math.abs returns wrong value for Integer.Min_VALUE

By | July 20, 2019


This code:


Returns -2147483648

Should it not return the absolute value as 2147483648 ?


Integer.MIN_VALUE is -2147483648, but the highest value a 32 bit integer can contain is +2147483647. Attempting to represent +2147483648 in a 32 bit int will effectively “roll over” to -2147483648. This is because, when using signed integers, the two’s complement binary representations of +2147483648 and -2147483648 are identical. This is not a problem, however, as +2147483648 is considered out of range.

For a little more reading on this matter, you might want to check out the Wikipedia article on Two’s complement.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *