What is the Math.abs function in Java?

The abs method takes one argument and returns the absolute valuethe non-negative value of the passed argument. The arguments can be int, long, float, or double.

abs is a static method present in the Math class.

Syntax

Math.abs(a);

Arguments

  • a: The argument from which the absolute value will be returned.

Return value

If the value of the passed argument is:

  • Negative, then the negative sign is removed and a positive value is returned.

  • Postive, then the value of the argument is returned.

  • NaN, then NaN will be returned.

  • an Infinite value, then Infinity will be returned.

Example

import java.lang.Math;
class AbsTest {
public static void main(String cmdArgs[]) {
int a = -20;
System.out.print("The absolute value of "+ a + " is ");
System.out.println(Math.abs(a));
double negativeInfinity = Double.NEGATIVE_INFINITY;
System.out.print("The absolute value of "+ negativeInfinity + " is ");
System.out.println(Math.abs(negativeInfinity));
int twelve = 12;
System.out.print("The absolute value of 12 is ");
System.out.println(Math.abs(twelve));
}
}

In the code above, we use the Math.abs function to find the absolute value of the numbers. The Math.abs will return:

  • 20 for the -20 argument.
  • Infinity for the -Infinity argument.
  • 12 for the 12 argument.

Free Resources