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

  • Context: Java 
  • Thread starter Thread starter Office_Shredder
  • Start date Start date
  • Tags Tags
    Java
Click For Summary

Discussion Overview

The discussion centers around the behavior of Java's Math.abs() method, specifically regarding its handling of the minimum integer value, Integer.MIN_VALUE. Participants explore the implications of this behavior, including the concept of integer overflow and design choices in programming languages.

Discussion Character

  • Technical explanation, Debate/contested

Main Points Raised

  • One participant notes that calling abs on Integer.MIN_VALUE results in the same negative value, raising a question about why this occurs.
  • Another participant attributes this behavior to integer overflow, suggesting that the magnitude of Integer.MIN_VALUE and Integer.MAX_VALUE plays a role.
  • A later reply expresses surprise at the decision not to raise an exception for this case, contrasting it with the C standard and suggesting that providing a definite value is a design improvement.
  • There is a mention of a design principle that advises against throwing exceptions for situations that cannot be resolved cleanly, which may relate to the behavior of Math.abs().

Areas of Agreement / Disagreement

Participants express differing views on the design choices made regarding the Math.abs() method, particularly whether returning a definite value is preferable to raising an exception. The discussion remains unresolved regarding the implications of these design choices.

Contextual Notes

Participants do not fully explore the mathematical implications of integer overflow or the specific design principles referenced, leaving some assumptions and definitions unaddressed.

Office_Shredder
Staff Emeritus
Science Advisor
Gold Member
Messages
5,706
Reaction score
1,592
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".
 

Similar threads

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