# Java Math.abs: Absolute Value

This Java example uses the Math.abs method, which computes an absolute value of its argument.**Math.abs, absolute value.** Consider the number -1. It has an absolute part—the value 1. With Math.abs we take this absolute value, making the number positive.

**With logical tests,** we can check for negative and positive numbers. But Math.abs streamlines this. It makes some programs simpler and easier to reason about.

**Absolute value.** Let us start. An absolute value is the number with no negative sign. If the number is already positive, no change is made. We first import java.lang.Math.

**Types:** Math.abs returns various types. These depend on the types passed to it. If we pass an int, we receive an int in return.

**Java program that uses Math.abs**
import java.lang.Math;
public class Program {
public static void main(String[] args) {*
// This version uses an int.
*int value = __Math.abs__(*-1*);
System.out.println(value);*
// This version uses a double.
*double value2 = __Math.abs__(*-1.23*);
System.out.println(value2);
int value3 = __Math.abs__(*1*);
System.out.println(value3);
}
}
**Output**
1
1.23
1

**Rewrite if-statement.** Sometimes we have logic that acts on positive and negative numbers in different ways. This can be rewritten with Math.abs in certain programs.

**Here:** The addAbsoluteValue adds if a number is positive, and subtracts if it is negative.

**Tip:** We can rewrite addAbsoluteValue with a call to Math.abs. This reduces code size and makes things clearer.

**Java program that rewrites if-statement with Math.abs**
public class Program {
static int addAbsoluteValue(int base, int number) {*
// Add number if it is positive.
// ... Subtract if it is negative.
*if (number > 0) {
return base + number;
} else {
return base - number;
}
}
public static void main(String[] args) {*
// Use our custom method and rewrite it with Math.abs.
*int result1 = addAbsoluteValue(5, -1);
int result2 = addAbsoluteValue(5, 10);
int result3 = 5 + __Math.abs__(-1);
int result4 = 5 + __Math.abs__(10);
System.out.println(result1);
System.out.println(result2);
System.out.println(result3);
System.out.println(result4);
}
}
**Output**
6
15
6
15

**Overloads.** In Java 8 we find overloaded versions of Math.abs for double, float, int and long. For values like byte and short, we can use the int overload.

Overload

**Performance.** In my tests, the performance of Math.abs is similar to an if-statement. I could not demonstrate any important differences.

**A summary.** With Math.abs we can simplify logic with a method call. This is simpler than an if-statement or other logical test. It leads to clearer programs, ones easier to comprehend.

© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.