Java Math abs()

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

Example

class Main {
  public static void main(String[] args) {

// print the absolute value System.out.println(Math.abs(-7.89));
} }

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:
    • int
    • double
    • float
    • long

Note: To learn more about int, double, float, and long, visit Java Data Types(Primitive).


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

class Main {
  public static void main(String[] args) {

    // create variables
    int a = 7;
    long b = -23333343;
    double c = 9.6777777;
    float d = -9.9f;

    // print the absolute value
    System.out.println(Math.abs(a));  // 7
    System.out.println(Math.abs(c));  // 9.6777777


    // print the value without negative sign
    System.out.println(Math.abs(b));  // 23333343
    System.out.println(Math.abs(d));  // 9.9
  }
}

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

class Main {
  public static void main(String[] args) {

    // create variables
    int a = -35;
    long b = -141224423L;
    double c = -9.6777777d;
    float d = -7.7f;

    // get the absolute value
    System.out.println(Math.abs(a));  // 35
    System.out.println(Math.abs(b));  // 141224423
    System.out.println(Math.abs(c));  // 9.6777777
    System.out.println(Math.abs(d));  // 7.7
  }
}

Here, we can see that the abs() method converts the negative value into a positive value.

Did you find this article helpful?