What is StrictMath.abs method in Java?
Overview
The StrictMath class as utility methods is used for performing basic numeric operations. It is present in the java.lang package.
Note: Read more about the
StrictMathclass here.
The abs method can be used to get the absolute value of the passed value.
Syntax
This method has four overridden methods:
public static double abs(double a)
public static float abs(float a)
public static int abs(int a)
public static long abs(long a)
Return value
-
If the argument is negative, then the argument’s negation is returned ( the negative value is converted to a positive value).
-
If the argument is positive then the same value is returned.
-
If the argument is
NaNthenNaNis returned.
Code
The below code explains how to use the abs method:
class StrictMathAbsExample {public static void main( String args[] ) {// create one double and one int variabledouble val1 = -10.45;int val2 = 10;// use StrictMath.abs methodSystem.out.println("StrictMath.abs(-10.45) : " + StrictMath.abs(val1));System.out.println("StrictMath.abs(10) : " + StrictMath.abs(val2));}}
Explanation
In the above code:
-
Lines 4 and 5: We create one double variable
val1and one int variableval2with values-10.45and10, respectively. -
Line 7: We use the
absmethod of theStrictMathclass to get the absolute value of theval1variable. Theval1contains the negative value-10.45so theabsmethod returns the negation of the value(10.45). -
Line 8: We use the
absmethod of theStrictMathclass to get the absolute value of theval2variable. Theval2contains the positive value10so, the same value is returned.