Home
Map
Math.abs: Absolute ValueUse the Math.abs method, which computes an absolute value of its argument.
Java
This page was last reviewed on May 9, 2022.
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.
Math
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. 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.
Detail 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
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.
if
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.
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
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 9, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.