• Post Reply Bookmark Topic Watch Topic
  • New Topic
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
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Lang package

 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

Please clarify.
 
Ranch Hand
Posts: 982
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
moose poop looks like football shaped elk poop. About the size of this tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic