Make a negative number positive
The Math.abs()
method is your go-to when you want to convert a negative number into positive:
A tricky case: Integer.MIN_VALUE
Unexpected behavior
The Math.abs()
method can throw you off if you try to apply it on Integer.MIN_VALUE
.
This behavior is due to the fact that Java's int type is a 32-bit signed integer. The most negative value can't flip into a positive one within this range.
Ternary operator for the rescue
When Math.abs
doubles down on Integer.MIN_VALUE
, you can count on the ternary operator:
Dealing with sums
When you need to treat all numbers as positive while summing them up, simply apply Math.abs()
within a loop:
This lets the sum reflect the total distance from zero, irrespective of the direction.
What is absolute value, anyway?
A little theory
In simple terms, the absolute value of a number is the distance from zero, regardless of whether you count to the left or the right.
A simple example
Consider two cities on a map, positioned 300km around a central point.
The absolute distance from any city to the center is 300km, no matter the direction.
Going large with BigInteger
For values beyond the range of int
, you can use BigInteger
.
Precision is key: dealing with float and double
Float or double?
Use Math.abs()
with float
or double
types in a breeze:
BigDecimal to tackle precision
If precision is a concern, opt for using BigDecimal
. It helps maintain the exact decimal representation:
Was this article helpful?