What is the Math.abs function in Java?
The abs method takes one argument and returns the 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, thenNaNwill be returned. -
an
Infinitevalue, thenInfinitywill 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:
20for the-20argument.Infinityfor the-Infinityargument.12for the12argument.