Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Math.abs(Integer.MIN_VALUE)

 
Yogesh Chhawasaria
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

It prints out
-2147483648
But shouldnt abs funct return only positive value or the absolute value.
Whats the catch here.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From the API documentation for java.lang.Math.abs(int):
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.

The second paragraph explains the strange border-line behaviour. So it would seem that in general you cannot just write Math.abs(i) for some int i. You should also test the returned result to see if it is Integer.MIN_VALUE before you continue with the calculations. I wonder why it was not done with a RuntimeException?
A similar thing occurs with Math.abs(long).
Nasty things, negative absolute values.
[ April 11, 2004: Message edited by: Barry Gaunt ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic