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
| Parameter | Type | Description |
|---|---|---|
| a | int, long, float, double | A 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.5The distance between two numbers:
void main() {
int a = 3, b = 10;
IO.println(Math.abs(a - b));
}Output:
7Notes
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
- Math.max() — Returns the larger of two numbers.
- Math.min() — Returns the smaller of two numbers.
- Math.floorMod() — A remainder that always has the sign of the divisor.
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.