Description

On this document we will be showing a java example on how to use the abs() method of Math Class. This method is overloaded in such a way that all possible data type is handled. Basically the abs() method returns the absolute value of a float value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. However below are some 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.

Method Syntax

public static datatype abs(datatype a)

As we have noted already the abs() method is overloaded, thus on the method signature above we have mentioned datatype which signifies that this method accepts any data type and will return the absolute value of the method argument reflecting the same data type as the input.

Method Returns

The abs() method returns the absolute value of the argument.

Compatibility

Requires Java 1.0 and up

Java Math abs() Example

Below is a java code demonstrates the use of abs() method of Math class. The example presented might be simple however it shows the behavior of the abs() method.

The above java example source code demonstrates the use of abs() method of Math class. We simply declare values of different values and we get the absolute value of those. This is to demonstrate on how the abs() method works on different data types.

Sample Output

Below is the sample output when you run the above example.

java lang Math abs() example output