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 Confusion 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.abs Confusion " Watch "Math.abs Confusion " New topic
Author

Math.abs Confusion

Akhilesh Yadav
Ranch Hand

Joined: Apr 04, 2006
Posts: 46
class s{
public static void main(String [] args){
System.out.println(Math.abs(-2147483648));
System.out.println(Math.abs(-2147483647));
}
}

out put is
-2147483648
2147483647

why the out put is difference ?
[ January 11, 2007: Message edited by: Akhilesh Yadav ]
Tanakorn Numrubporn
Ranch Hand

Joined: Dec 11, 2006
Posts: 81
Originally posted by Akhilesh Yadav:
class s{
public static void main(String [] args){
System.out.println(Math.abs(-2147483648));
System.out.println(Math.abs(-2147483647));
}
}

out put is
-2147483648
2147483647

why the out put is difference ?


the API doc of Math class in abs(int a) static method is said that:
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.

It told you that if you use Math.abs(Integer.MIN_VALUE) you will get the result equal Integer.MIN_VALUE, which equal -2147483648.

But if you change the problem statement from:
System.out.println(Math.abs(-2147483648));
TO
System.out.println(Math.abs(-2147483648L));

The result is will become to 2147483648, which is not the negative value, you know why. Please go to see API and you will get enlightenment.

Cheers
Tanakorn
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Math.abs Confusion
 
Similar Threads
Why Math.abs() is giving negative output??????
Math.abs(Integer.MIN_VALUE)) not returning abs val
Math.abs(Integer.MIN_VALUE) return a negative vaue,why?
Math.abs()
Math.round()