aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes about Math.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 "about Math.abs()" Watch "about Math.abs()" New topic
Author

about Math.abs()

wei liu
Ranch Hand

Joined: Dec 06, 2001
Posts: 56
public class ADirtyOne
{
public static void main(String args[])
{
System.out.println(Math.abs(Integer.MIN_VALUE));
}
}
an attempt to compile and run the above class will
1 Cause a compiler error.
2 Cause no error and the value printed on the screen is less than zero.
3 Cause no error and the value printed on the screen is one more than Integer.MAX_VALUE
4 Will throw a runtime exception due to overflow - Integer.MAX_VALUE is less in magnitue than Integer.MIN_VALUE.
-------------
the ans is 2nd. why? I thought it would be positive , but actually the running rsult is -2147483648.if I changed the code as
System.out.println(Integer.MIN_VALUE), the result is still be -2147483648 which I understand.

Jim Hall
Ranch Hand

Joined: Nov 29, 2001
Posts: 162
The answer is in the API:
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.
This is because the method returns the same type as the argument to the abs() method. It is impossible to represent the Integer.MIN_VALUE as a positive value, because the max value is always one less than its negative counterpart.
[This message has been edited by Jim Hall (edited December 29, 2001).]
paul wheaton
Trailboss

Joined: Dec 14, 1998
Posts: 20729
    ∞

Just to tack on a bit to what Jim said:
ints cover the range of -2147483648 to 2147483647
The absolute value of -2147483648 is 2147483648 which cannot be stored in an int.

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
I guess this method just changes 1s for 0s and viceversa and adds 1.
But doing that to x10000000 ends up in the same result.


SCJP2. Please Indent your code using UBB Code
 
 
subject: about Math.abs()