posted 17 years ago
Ken,
Thank you for using my exam.
The method name abs is overloaded. There are versions that accept one argument of type int, long, float or double. The type of the return value is the same as the argument type as long as the argument is one of the four types mentioned earlier: int, long, float or double. The magnitude of Integer.MIN_VALUE is one greater than the magnitude of Integer.MAX_VALUE; therefore, the absolute value of Integer.MIN_VALUE exceeds the range of Integer.MAX_VALUE. Due to the limited range of type int, the two's complement of Integer.MIN_VALUE is surprisingly Integer.MIN_VALUE.
If the argument is Short.MIN_VALUE, then the type of the argument will be promoted to type int by method invocation conversion. More specifically, the argument of type short that has the value Short.MIN_VALUE will be promoted to type int and the value will be -32768. The absolute value of negative 32768 is positive 32768, and that positive value is well within the range of type int; so that's the value that will be returned by the abs method.
The abs method is able to correctly calculate the absolute value of Short.MIN_VALUE, because method invocation conversion promotes the type of the argument from type short to type int. The abs method does not correctly calculate the absolute value of Integer.MIN_VALUE, because the argument is not promoted to a type that has a range that is wide enough to accommodate the absolute value of Integer.MIN_VALUE.
[ May 26, 2007: Message edited by: Dan Chisholm ]
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>