Skip to content

Java Math API

Java Math class — methods for basic numeric operations.

1 class · 9 methods

Math

9 methods

The Math class contains methods for performing basic numeric operations.

static int abs(int a)

Return the absolute value of an int. Long.MIN_VALUE remains negative.

Parameters

NameTypeDescription
aintArgument.

Returns

int

Example

java
Math.abs(-5)   // 5
Math.abs(5)    // 5
Math.abs(-2147483648)  // -2147483648 (overflow!)
static int max(int a, int b)

Return the greater of two int values.

Parameters

NameTypeDescription
aintFirst value.
bintSecond value.

Returns

int

Example

java
Math.max(3, 7)   // 7
Math.max(-1, -5)  // -1
static int min(int a, int b)

Return the smaller of two int values.

Parameters

NameTypeDescription
aintFirst value.
bintSecond value.

Returns

int

Example

java
Math.min(3, 7)   // 3
Math.min(-1, -5)  // -5
static double pow(double a, double b)

Return the value of a raised to the power of b.

Parameters

NameTypeDescription
adoubleBase.
bdoubleExponent.

Returns

double

Example

java
Math.pow(2, 10)   // 1024.0
Math.pow(9, 0.5)   // 3.0
Math.pow(2, -1)    // 0.5
static double sqrt(double a)

Return the correctly rounded positive square root of a. NaN if a < 0.

Parameters

NameTypeDescription
adoubleValue.

Returns

double

Example

java
Math.sqrt(9)    // 3.0
Math.sqrt(2)    // 1.4142135623730951
Math.sqrt(-1)   // NaN
static long round(double a)

Return the closest long to a, with ties rounding to positive infinity.

Parameters

NameTypeDescription
adoubleValue to round.

Returns

long

Example

java
Math.round(2.4)   // 2
Math.round(2.5)   // 3
Math.round(-2.5)  // -2
static double ceil(double a)

Return the smallest (closest to negative infinity) double that is greater than or equal to a and equal to a mathematical integer.

Parameters

NameTypeDescription
adoubleValue.

Returns

double

Example

java
Math.ceil(2.1)   // 3.0
Math.ceil(-2.9)  // -2.0
static double floor(double a)

Return the largest (closest to positive infinity) double that is less than or equal to a and equal to a mathematical integer.

Parameters

NameTypeDescription
adoubleValue.

Returns

double

Example

java
Math.floor(2.9)   // 2.0
Math.floor(-2.1)  // -3.0
static double random()

Return a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Returns

double

Example

java
Math.random()                    // e.g. 0.5819...
(int)(Math.random() * 6) + 1     // 1..6 (dice)
Math.random() * 100              // 0..99.99...