Math.abs
, absolute valueConsider 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.
To 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
.
Math.abs
returns various types. These depend on the types passed to it. If we pass an int
, we receive an int
in return.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); } }1 1.23 1
if
-statementSometimes we have logic that acts on positive and negative numbers in different ways. This can be rewritten with Math.abs
in certain programs.
addAbsoluteValue
adds if a number is positive, and subtracts if it is negative.addAbsoluteValue
with a call to Math.abs
. This reduces code size and makes things clearer.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); } }6 15 6 15
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.
In my tests, the performance of Math.abs
is similar to an if
-statement. I could not demonstrate any important differences.
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.