Java Tutorial Java Advanced Java References

Java Math - abs() Method



The Java abs() method returns the absolute value (positive value) of the specified number. The method can be overloaded and it can take int, double, float and long arguments. In special cases it returns the following:

  • If the argument is equal to the value of Integer.MIN_VALUE or Long.MIN_VALUE, the most negative representable int value or long value, the result is that same value, which is negative.
  • 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

public static int abs(int arg)
public static long abs(long arg)
public static float abs(float arg)
public static double abs(double arg)

Parameters

arg Specify a number whose absolute value need to be determined.

Return Value

Returns the absolute value (positive value) of the argument.

Exception

NA.

Example:

In the example below, abs() method returns the absolute value (positive value) of the specified number.

public class MyClass {
 public static void main(String[] args) {
  System.out.println(Math.abs(10)); 
  System.out.println(Math.abs(-10)); 
  System.out.println(Math.abs(-5.5)); 
  System.out.println(Math.abs(-5.5f));   
 }
}

The output of the above code will be:

10
10
5.5
5.5

❮ Java Math Methods