java.lang.StrictMath abs(double a)
Description
The abs(double a) method of StrictMath class returns the absolute value of a double value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. Special cases:
- If the argument is positive zero or negative zero, the result is positive zero.
- If the argument is infinite, the result is positive infinity.
- If the argument is NaN, the result is NaN.
Notes:
As implied by the above, one valid implementation of this method is given by the expression below which computes a double with the same exponent and significand as the argument but with a guaranteed zero sign bit indicating a positive value:
Double.longBitsToDouble((Double.doubleToRawLongBits(a)<<1)>>>1)
The abs(double a) method of StrictMath class is static thus it should be accessed statically which means the we would be calling this method in this format:
StrictMath.abs(double a)
Non static method is usually called by just declaring method_name(argument) however in this case since the method is static, it should be called by appending the class name as suffix. We will be encountering a compilation problem if we call the java compare method non statically.
Method Syntax
public static double abs(double a)
Method Argument
| Data Type | Parameter | Description |
|---|---|---|
| double | a | the argument whose absolute value is to be determined. |
Method Returns
The abs(double a) method returns the absolute value of the argument.
Compatibility
Requires Java 1.3 and up
Java StrictMath abs(double a) Example
Below is a java code demonstrates the use of abs(double a) method of StrictMath class.
package com.javatutorialhq.java.examples;
import java.util.Scanner;
/*
* A java example source code to demonstrate
* the use of abs(double a) method of Math class
*/
public class StrictMathAbsDoubleExample {
public static void main(String[] args) {
// Ask user input (double)
System.out.print("Enter a double:");
// declare the scanner object
Scanner scan = new Scanner(System.in);
// use scanner to get the user input and store it to a variable
double dValue = scan.nextDouble();
// close the scanner object
scan.close();
// get the absolute value of the user input
double result = StrictMath.abs(dValue);
// print the result
System.out.println("result: "+result);
}
}
