File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Math.abs(Integer.MIN_VALUE) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Math.abs(Integer.MIN_VALUE)" Watch "Math.abs(Integer.MIN_VALUE)" New topic
Author

Math.abs(Integer.MIN_VALUE)

Yogesh Chhawasaria
Ranch Hand

Joined: Apr 02, 2004
Posts: 53

It prints out
-2147483648
But shouldnt abs funct return only positive value or the absolute value.
Whats the catch here.


When you have eliminated all which is impossible, then whatever remains, however improbable, must be the truth.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
From the API documentation for java.lang.Math.abs(int):
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.

The second paragraph explains the strange border-line behaviour. So it would seem that in general you cannot just write Math.abs(i) for some int i. You should also test the returned result to see if it is Integer.MIN_VALUE before you continue with the calculations. I wonder why it was not done with a RuntimeException?
A similar thing occurs with Math.abs(long).
Nasty things, negative absolute values.
[ April 11, 2004: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Math.abs(Integer.MIN_VALUE)