programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin

Lang package

Ranch Hand
Posts: 102
• Number of slices to send:
Optional 'thank-you' note:
Code:
--------------------------------------------------------------
1 class Q41
2 {
3 public static void main(String arg[])
4 {
5 System.out.println(Math.abs(-2147483648);
6 }
7 }
---------------------------------------------------------------

Why am I getting the following output
-2147483648

Ranch Hand
Posts: 980
• Number of slices to send:
Optional 'thank-you' note:
Hi,

If you look in the API of math class..

int java.lang.Math.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.

Hope you got it

Ranch Hand
Posts: 66
• Number of slices to send:
Optional 'thank-you' note:
System.out.println(Math.abs(-2147483648);

The following would be the steps for abs function

1. Convert a negative number to positive
2. in this case by doing so, we would have 2147483648, which has 1 as the sign bit, to find the value, we need to take the two's complement, which will give us back 2147483648. There by we understand that it is -2147483648 that is returned by the abs function on -2147483648

-2147483648 = -(2 to the power of 31)

The max positive range for integers is 2147483647 (2 to the power of 31 -1).

abs(-2 to the power of 31) returns 2 to the power of 31, which has 1 as the sign bit, as described above by performing 2's complement, we get it as -(2 to the power of 31).

Hope this explanation helps!

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.