Math.abs(INT_MIN_VALUE) gives a negative answer WHY? ANY EXPLAINATION. ARUN
ARUN
shadow liu
Ranch Hand
Joined: Mar 19, 2001
Posts: 33
posted
0
In \jdk1.3\src\java\lang\Math.java it says: /*********start***********/ /** .... * Note that if the argument is equal to the value of * <code>Integer.MIN_VALUE</code>, the most negative representable * <code>int</code> value, the result is that same value, which is * negative. * * @param a an <code>int</code> value. * @return the absolute value of the argument. * @see java.lang.Integer#MIN_VALUE */ public static int abs(int a) { return (a < 0) ? -a : a; } /**************end***************/ IMHO, since the integer range is -2**31 to 2**31-1, which means -2**31 is the only number that do not have a opposite INTEGER value, so JDK leave it unchanged. Just my guess.
Java uses two's complement to represent integral values. To get the abs value of -41 we need to convert a negative value (-41) to a positive value (41). Here is how its done using two's complement. Note that I'm using a byte width for the purpose of discussion.
We see here that the abs(-41) value is 41. Now back to your original concern using Integer.MIN_VALUE:
Hope this helps
------------------ ~James Baud He who asks, is a fool for five minutes; but, he who does not ask, remains a fool forever. (Chinese proverb)
<B>~James Baud</B><P>He who asks, is a fool for five minutes;<BR>but, he who does not ask, remains a fool forever. (Chinese proverb)