Languages
[Edit]
EN

Java - Math.abs() method example

3 points
Created by:
Palusbug
515

The Math.abs() function returns the absolute value of a number. 

The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

Popular usage examples:

public class MathExample {

    public static void main(String[] args) {
        System.out.println( Math.abs(2)     ); // 2
        System.out.println( Math.abs(-2)    ); // 2

        System.out.println( Math.abs(2.54)  ); // 2.54
        System.out.println( Math.abs(-2.54) ); // 2.54

        System.out.println( Math.abs(0)     ); // 0
        System.out.println( Math.abs(3 + 5) ); // 8
        System.out.println( Math.abs(3 - 5) ); // 2
    }
}

1. Documentation

Syntax
package java.lang;

public final class Math {

    public static int abs(int number) { ... }
    public static long abs(long number) { ... }
    public static float abs(float number) { ... }
    public static double abs(double number) { ... }

}

Note: Classes in the java.lang package are imported automatically, so it is not necessary to do it manually - we use just Math.abs() call.

Parametersnumber - double, float, int, or long value (primitive value).
ResultThe absolute value calculated from the number (primitive value).
Description

Math.abs() is a static method that takes only one parameter and returns absolute number parameter value. The absolute value of the number x denoted |x|, is the non-negative value of x without regard to its sign.

2. Math.abs() custom implementation

public class CustomMath {

    static double abs(double x) {
        if (x < 0) {
            return -x;
        }
        return x;
    }

    public static void main(String[] args) {
        System.out.println( abs(2.0) ); // 2.0
        System.out.println( abs(-2.0)); // 2.0
        System.out.println( abs(0.0) ); // 0.0
    }
}
Note: there are few ways to change sign to opposite if (x < 0) is true:
  • x = -x
  • x *= -1
  • x = ~x + 1(not for double)

References

  1. Absolute value - wikipedia
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - Math.abs()

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join