posted 17 years ago
The range of an int is -2^31 to (2^31)-1, which is -2147483648 to 2147483647. Note that the magnitude of the negative bound is one greater than that of the positive bound.
So the absolute value of Integer.MIN_VALUE is actually greater than Integer.MAX_VALUE. In particular, we might expect the absolute value to be +2147483648, but this is one greater than what can be expressed as a positive int, so this overflows to Integer.MIN_VALUE.
In terms of twos complement, flipping the bits of Integer.MIN_VALUE results in Integer.MAX_VALUE, then adding 1 causes the overflow. Note the output from the code below...
This is not a concern when a short is passed to the Math.abs(int) method, because the short is widened to type int, which can easily accomodate Short.MAX_VALUE + 1.
[ May 12, 2005: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org