programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

Math class method abs()

Greenhorn
Posts: 2
• Number of slices to send:
Optional 'thank-you' note:
Math.abs(INT_MIN_VALUE) gives a negative answer WHY? ANY EXPLAINATION.
ARUN

Ranch Hand
Posts: 33
• Number of slices to send:
Optional 'thank-you' note:
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.

Ranch Hand
Posts: 60
• Number of slices to send:
Optional 'thank-you' note:

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)

 Politics is a circus designed to distract you from what is really going on. So is this tiny ad: a bit of art, as a gift, the permaculture playing cards https://gardener-gift.com