Java Math.abs() with Examples

Oct 12, 2019 · 3 mins read

The java.lang.Math class that comes bundled with Java contains various methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions.

Math.abs(…) method is part of the Math class. It is used for finding the absolute value of a number. Absolute value is the magnitude of a real number without regard to its sign. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.


Math.abs(…) method is overloaded. Here are the method signatures:

public static int abs(int a)

public static long abs(long a)

public static float abs(float a)

public static double abs(double a)

Note just like all other methods on the Math class, Math.abs(…) is a static method so you can call it directly on the Math class. The overloaded methods can take all primitive number types and the return type is the same as that of the argument.

int result = Math.abs(-3); // result = 3

Code Example

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

    private static void absolute() {
        System.out.println(Math.abs(3)); // 3

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

        System.out.println(Math.abs(1000L)); // 1000

        System.out.println(Math.abs(2.0f)); // 2.0

        System.out.println(Math.abs(-2.0f)); // 2.0

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

        System.out.println(Math.abs(Double.NEGATIVE_INFINITY)); // + Infinity



There you have it. Hope you found this tutorial useful!

Special cases

For floating-point numbers i.e. float or double:

  • 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.

If you need more detailed information, please see Javadocs. It’s worth noting that the Math class in Java contains several other useful methods for arithmetic, logarithms and trignometric operations.

See also

Here’s a short youtube video that walks through several methods of the Math class.

<iframe width="560" height="315" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
#math-class #java

You May Also Enjoy

If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you!