Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Math.min()

Returns the smaller of two numbers.

Available since: Java 1.0

Syntax

static int min(int a, int b)

Parameters

ParameterTypeDescription
aint, long, float, doubleThe first number.
bsame type as aThe second number of the same type.

Return value

same type as aThe smaller of the two values.

Examples

The smaller of two:

void main() {
    IO.println(Math.min(7, 12));
    IO.println(Math.min(-1.5, 0.0));
}

Output:

7
-1.5

Clamping a value from above and below:

void main() {
    int volume = 140;
    int clamped = Math.max(0, Math.min(100, volume));
    IO.println(clamped);
    IO.println(Math.clamp(-20, 0, 100));
}

Output:

100
0

Notes

Since Java 21 there is a ready Math.clamp(value, min, max) for limiting a value to a range.

See also

  • Math.max() — Returns the larger of two numbers.
  • Math.abs() — Returns the absolute value of a number — the value without a minus sign.

Related recipes

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.