# Math class method abs()

arun sabharwal

Greenhorn

Posts: 2

shadow liu

Ranch Hand

Posts: 33

posted 14 years ago

- 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.

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.

James Baud

Ranch Hand

Posts: 60

posted 14 years ago

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

------------------

He who asks, is a fool for five minutes;

but, he who does not ask, remains a fool forever. (Chinese proverb)

- 0

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)

With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |