Languages
[Edit]
EN

Java - Math.abs() method example

3 points
Created by:
Dirask Admin - Marwin
1430

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

Java - Math object

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