Java - Math.abs() Method



Description

The method gives the absolute value of the argument. The argument can be int, float, long, double, short, byte. 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.

Syntax

Following are all the variants of this method −

double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)

Parameters

Here is the detail of parameters −

  • Any primitive data type.

Return Value

  • This method Returns the absolute value of the argument.

Example 1

In this example, we're showing the usage of Math.abs() method to get absolute value of an int. We've created two Integer variable x and y and initialized them with negative and positive values. Then using Math.abs() method we're printing the absolute value of the integers.

public class Test { 
   public static void main(String args[]) {
      Integer a = -8;
      Integer b = 8;

      System.out.println(Math.abs(a));
      System.out.println(Math.abs(b));    
   }
}

This will produce the following result −

Output

8
8

Example 2

In this example, we're showing the usage of Math.abs() method to get absolute value of a long. We've created two Long variable x and y and initialized them with negative and positive values. Then using Math.abs() method we're printing the absolute value of longs.

public class Test { 
   public static void main(String args[]) {
      Long a = -8L;
      Long b = 8L;

      System.out.println(Math.abs(a));
      System.out.println(Math.abs(b));    
   }
}

This will produce the following result −

Output

8
8

Example 3

In this example, we're showing the usage of Math.abs() method to get absolute value of a double. We've created two Double variable x and y and initialized them with negative and positive values. Then using Math.abs() method we're printing the absolute value of the doubles.

public class Test { 
   public static void main(String args[]) {
      Double a = -8.0;
      Double b = 8.0;

      System.out.println(Math.abs(a));
      System.out.println(Math.abs(b));    
   }
}

This will produce the following result −

Output

8.0
8.0
java_numbers.htm
Advertisements