7.25.2014

Math: abs() - Returns the absolute value of a number

To get the absolute value of a number, java.lang.Math class defines four static overloaded abs() methods that takes an int or long or float or double as its only argument and returns the absolute value of that passed argument.

The following rules apply for this methods:
  • If the passed argument is positive, then this method returns the argument.
  • If the passed argument is negative, this method returns the negation of the argument.
  • 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.

Method Declaration:
public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)

Live Example:
import static java.lang.Double.NaN;

public class Demo {
    public static void main(String[] args) {
        System.out.println("Absolute value of -0 is " + Math.abs(-0));
        System.out.println("Absolute value of 0 is " + Math.abs(0));
        System.out.println("Absolute value of 2 is " + Math.abs(2));
        System.out.println("Absolute value of -111L is " + Math.abs(-111L));
        System.out.println("Absolute value of 5.96 is " + Math.abs(5.96));
        System.out.println("Absolute value of -20.5F is " + Math.abs(-20.5F));
        System.out.println("Absolute value of NaN is " + Math.abs(NaN));
    }  
}

Output: 
Absolute value of -0 is 0
Absolute value of 0 is 0
Absolute value of 2 is 2
Absolute value of -111L is 111
Absolute value of 5.96 is 5.96
Absolute value of -20.5F is 20.5
Absolute value of NaN is NaN

Use the social sharing button below to spread the knowledge among others.

0 comments:

Post a Comment