According to the API, abs() checks to see if the value is positive. If so it returns the number, if not, it returns -1 * the number. Getting into the bits, -1 * Integer.MIN_VALUE = Integer.MIN_VALUE.
Here's why...(I'll use only four bits to keep it simple) -1 in binary (with two's complement notation) is
1111. To negate,
you should subtract 1, then flip all the bits.
1111 - 1 = 1110 -> (flip bits) -> 0001 //works!
The largest neg number we can represent with four bits is -8, in two's complement:
1000 -> (flip) -> 0111 + 1 = 1000
Study the last line and the rest follows, but since I used to hate when profs used that line on me, I'll finish. To negate, subtract 1 and flip bits:
1000 - 1 = 0111 -> (flip) -> 1000 //evaluates to -8!
If you still don't believe me, try this code:
public class
Test {
public static void main (String args[]) {
System.out.println(Integer.MIN_VALUE * -1);
System.out.println(-2147483648 * -1);
}
}
System.out : -2147483648
System.out : -2147483648
Here's a cut 'n paste from the JDK 1.3 API
abs
public static int abs(int a)
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.
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.
Parameters:
a - an int value.
Returns:
the absolute value of the argument.
See Also:
Integer.MIN_VALUE