Java Understanding Java's Math.abs() Method: Solving the Minimum Integer Value Issue

  • Thread starter Thread starter Office_Shredder
  • Start date Start date
  • Tags Tags
    Java
Click For Summary
The discussion centers on the behavior of the absolute value function in Java, specifically how it handles the integer value Integer.MIN_VALUE. When the absolute value of Integer.MIN_VALUE is calculated, it returns the same negative value due to integer overflow, rather than raising an exception. Participants express surprise at this design choice, noting that it could have been handled differently, such as by throwing an exception. However, some acknowledge that providing a definite value instead of an exception is an improvement over the C standard. The conversation touches on the design principle of avoiding exceptions for situations that cannot be resolved cleanly.
Office_Shredder
Staff Emeritus
Science Advisor
Gold Member
Messages
5,705
Reaction score
1,589
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)

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:
Technology news on Phys.org
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.
 
Thanks!
 
Hurkyl said:
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".
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 2 ·
Replies
2
Views
6K
  • · Replies 4 ·
Replies
4
Views
3K