The abs() method returns the absolute value of the specified value.
Example
Syntax of Math.abs()
The syntax of the abs() method is:
Math.abs(num)
Here, abs() is a static method. Hence, we are accessing the method using the class name, Math.
abs() Parameters
The abs() method takes a single parameter.
- num - number whose absolute value is to be returned. The number can be:
intdoublefloatlong
abs() Return Value
- returns the absolute value of the specified number
- returns the positive value if the specified number is negative
Example 1: Java Math abs() with Positive Numbers
In the above example, we have imported the java.lang.Math package. This is important if we want to use methods of the Math class. Notice the expression,
Math.abs(a)
Here, we have directly used the class name to call the method. It is because abs() is a static method.
Example 2: Java Math abs() with Negative Numbers
Here, we can see that the abs() method converts the negative value into a positive value.