Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Math.abs — absolute value

Find the absolute value of a number, compare floating-point values within a tolerance, and handle the smallest integer values correctly.

Version: Java SE 21

Syntax

Math.abs(a)

Overloads in java.lang.Math (Java SE 21):
public static int abs(int a)
public static long abs(long a)
public static float abs(float a)
public static double abs(double a)

Math.abs(a) returns the absolute value of a, its distance from zero, when that result can be represented in the return type. It is a static method of java.lang.Math, so no object or import is needed. Java SE 21 has four overloads, for int, long, float, and double. The compiler selects an overload based on the argument type; the return type matches the selected overload's parameter type.

Watch out for integer minimums: Math.abs(Integer.MIN_VALUE) and Math.abs(Long.MIN_VALUE) return the same negative value they received because the positive counterpart does not fit in the type. If you want to detect overflow instead of getting a negative result, use Math.absExact(a) for int or long: it throws ArithmeticException for the corresponding minimum value.

For float and double, either -0.0 or +0.0 gives positive zero, either infinity gives positive infinity, and NaN stays NaN.

To compare two finite floating-point values, use Math.abs(a - b) <= tolerance. The <= operator includes the boundary: a difference equal to the tolerance is accepted. Choose a finite, nonnegative absolute tolerance that suits the scale and units of your data; no single value fits every case. If the computed difference is NaN, the comparison returns false.

Examples

public class AbsoluteValueDemo {
    public static void main(String[] args) {
        double actual = 0.1 + 0.2;
        double expected = 0.3;
        double tolerance = 1e-9;

        System.out.println(actual == expected);
        System.out.println(Math.abs(actual - expected) <= tolerance);
        System.out.println(Math.abs(-7));
        System.out.println(Math.abs(Integer.MIN_VALUE));
    }
}

Result

false
true
7
-2147483648

Floating-point rounding makes `0.1 + 0.2` differ from `0.3`, but the difference is within `1e-9`. The last two lines show a typical `int` result and the minimum-value case.

Related lessons

  • Java · Lesson 6 · Basic · Version: 2

Sources