The abs
method takes one argument and returns the int
, long
, float
, or double
.
abs
is a static
method present in the Math
class.
Math.abs(a);
a
: The argument from which the absolute value will be returned.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.
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.