File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Math class method abs() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Math class method abs()" Watch "Math class method abs()" New topic

Math class method abs()

arun sabharwal

Joined: Mar 20, 2001
Posts: 2
Math.abs(INT_MIN_VALUE) gives a negative answer WHY? ANY EXPLAINATION.

shadow liu
Ranch Hand

Joined: Mar 19, 2001
Posts: 33
In \jdk1.3\src\java\lang\
it says:
* 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;
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.
James Baud
Ranch Hand

Joined: Jan 06, 2001
Posts: 60

Math.abs(Integer.MIN_VALUE) returns Integer.MIN_VALUE

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)
I agree. Here's the link:
subject: Math class method abs()
It's not a secret anymore!