File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes simple one?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "simple one??" Watch "simple one??" New topic

simple one??

Harish Babu.N

Joined: Oct 12, 2000
Posts: 11
public class AQuestion

public static void main(String args[])

System.out.println("the abs value is " + Math.abs(Integer.MIN_VALUE));

on running the program o/p -2147483648 is shown even after saying abs(int).why is this?
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
Per the Java API:
public static int abs(int a)
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.
a - an int value.
the absolute value of the argument.

"JavaRanch, where the deer and the Certified play" - David O'Meara
Sean MacLean
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
Very interesting, isn't it? The reason is because the value returned by "Integer.MIN_VALUE" is in itself an int. If you look in the Java api at the values of Integer.MIN_VALUE and Integer.MAX_VALUE you'll see this.
Integer.MIN_VALUE = -2147483648
Integer.MAX_VALUE = 2147483647
So when you call Math.abs and pass it an int it wants to return an int. The problem is that the absoulte value of -2147483648 is 2147483648 which is one digit too large to fit in an int! So, to resolve the problem, cast the Integer.MIN_VALUE to a long before calling Math.abs, like so,
System.out.println("Value: " + Math.abs((long)Integer.MIN_VALUE));
I hope this clears things up for you
Sean MacLean
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
I was just poking around the api as well, since this started a brief discussion with a collegue as to what the method was actually doing ( bit shifting, casting up then down, etc). It's rather funny to see that the method is so trivial and they've simply handled this particular case as the 'one exception'.
I agree. Here's the link:
subject: simple one??
It's not a secret anymore!