• Post Reply Bookmark Topic Watch Topic
  • New Topic

Math.abs(int x)  RSS feed

 
Naresh Chaurasia
Ranch Hand
Posts: 361
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is the output of following program negative.



The output is -2147483648
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the API docs (our friend)


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 - the argument whose absolute value is to be determined
Returns:
the absolute value of the argument.



The absolute value of Integer.MIN_VALUE can not represented as a positive value as a Java int.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

2147483648
2147483647
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because of a vagary of two's complement numbers. If you negate the most negative value you get the same value back.
You create a (negative) two's complement number by subtracting it from 2ⁿ where n is the number of bits.That is 2³¹ subtracted from 2³², and you can see you get 2³¹ back. So negating MIN_VALUE gives you MIN_VALUE back.
 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

80000000
7fffffff

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!