Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Math.abs()

Returns the absolute value of a number — the value without a minus sign.

Available since: Java 1.0

Syntax

static int abs(int a)

Parameters

ParameterTypeDescription
aint, long, float, doubleA number of any numeric type.

Return value

same type as aA non-negative number of the same type.

Examples

Absolute value of an integer and a decimal:

void main() {
    IO.println(Math.abs(-42));
    IO.println(Math.abs(3.5));
}

Output:

42
3.5

The distance between two numbers:

void main() {
    int a = 3, b = 10;
    IO.println(Math.abs(a - b));
}

Output:

7

Notes

A trap: Math.abs(Integer.MIN_VALUE) returns the negative Integer.MIN_VALUE, because a positive number of that size does not fit in an int. If it matters, use Math.absExact(), which throws ArithmeticException.

See also

In the tutorial

  • Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.

Thanks for reading!

Donate to the site — we work hard for you.