This week's giveaway is in the Spring forum. We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line! See this thread for details.

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. Parameters: a - an int value. Returns: the absolute value of the argument.

"JavaRanch, where the deer and the Certified play" - David O'Meara

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

Sean MacLean
author
Ranch Hand

Joined: Nov 07, 2000
Posts: 621

posted

0

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'. Sean