Java Math.abs()

  • #1
Office_Shredder
Staff Emeritus
Science Advisor
Gold Member
3,997
214
When you take the absolute value of an integer value:

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Math.html#abs(int) [Broken]

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.
Wondering if anyone can explain what abs does that makes it fail on the minimum integer value
 
Last edited by a moderator:

Answers and Replies

  • #2
Hurkyl
Staff Emeritus
Science Advisor
Gold Member
14,916
19
Integer overflow. Check the magnitude of Integer.MIN_VALUE and Integer.MAX_VALUE.

I'm surprised they chose that, instead of raising an exception. Ah well.
 
  • #3
Office_Shredder
Staff Emeritus
Science Advisor
Gold Member
3,997
214
Thanks!
 
  • #4
AlephZero
Science Advisor
Homework Helper
6,994
291
I'm surprised they chose that, instead of raising an exception. Ah well.
At least they chose some definite value, which is an improvement on the C standard.

Maybe this is an example of the design principle, "don't throw exceptions for things that are impossible to fix cleanly even if you catch them".
 

Related Threads on Java Math.abs()

Replies
2
Views
10K
  • Last Post
Replies
9
Views
2K
  • Last Post
Replies
2
Views
1K
  • Last Post
Replies
2
Views
2K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
9
Views
2K
  • Last Post
Replies
18
Views
4K
  • Last Post
Replies
4
Views
999
  • Last Post
Replies
1
Views
3K
  • Last Post
Replies
3
Views
2K
Top