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
StrictMath
class here.
The abs
method can be used to get the absolute value of the passed value.
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)
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 NaN
then NaN
is returned.
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));}}
In the above code:
Lines 4 and 5: We create one double variable val1
and one int variable val2
with values -10.45
and 10
, respectively.
Line 7: We use the abs
method of the StrictMath
class to get the absolute value of the val1
variable. The val1
contains the negative value -10.45
so the abs
method returns the negation of the value( 10.45
).
Line 8: We use the abs
method of the StrictMath
class to get the absolute value of the val2
variable. The val2
contains the positive value 10
so, the same value is returned.