Explain Codes LogoExplain Codes Logo

Make a negative number positive

java
math-abs
biginteger
ternary-operator
Anton ShumikhinbyAnton Shumikhin·Aug 4, 2024
TLDR

The Math.abs() method is your go-to when you want to convert a negative number into positive:

int positive = Math.abs(-5); // Now positive holds 5, not negative thoughts.

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.

int minValue = Integer.MIN_VALUE; int positiveMinValue = Math.abs(minValue); // *gasp* It's still negative!

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:

int x = Integer.MIN_VALUE; int positiveX = (x < 0) ? -x : x; // If x is less than 0, make it -x. If not, keep it. It's that simple!

Dealing with sums

When you need to treat all numbers as positive while summing them up, simply apply Math.abs() within a loop:

int sum = 0; for (int number : numbersArray) { sum += Math.abs(number); // Turning negatives into positives. You could say this code is an optimist.

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.

City A (-300km) ------------------ 0 ------------------ City B (+300km)

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.

BigInteger bigNegative = new BigInteger("-1234567890123456789"); BigInteger bigPositive = bigNegative.abs(); // Now that's what you call a BIG positive!

Precision is key: dealing with float and double

Float or double?

Use Math.abs() with float or double types in a breeze:

double negativeDouble = -42.0; double positiveDouble = Math.abs(negativeDouble); // Turning the Hitchhiker's Guide fans into positive ones.

BigDecimal to tackle precision

If precision is a concern, opt for using BigDecimal. It helps maintain the exact decimal representation:

BigDecimal piNegative = new BigDecimal("-3.14159265358979323846"); BigDecimal piPositive = piNegative.abs(); // The pie is positive now, serve it with a smile!