Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Math.clamp()

Limits a number to a range: below min returns min, above max returns max.

Available since: Java 21

Syntax

public static int clamp(long value, int min, int max)

Parameters

ParameterTypeDescription
valuelong, double, floatThe original number.
minint, long, double, floatThe lower bound.
maxsame type as minThe upper bound, not less than min.

Return value

same type as minA number between min and max.

Examples

A percentage that stays within 0–100:

void main() {
    IO.println(Math.clamp(150, 0, 100));
    IO.println(Math.clamp(-5, 0, 100));
    IO.println(Math.clamp(42, 0, 100));
}

Output:

100
0
42

Decimal values, for example a volume from 0 to 1:

void main() {
    double volume = 1.7;
    IO.println(Math.clamp(volume, 0.0, 1.0));
    IO.println(Math.clamp(0.25, 0.0, 1.0));
}

Output:

1.0
0.25

If min is greater than max, the method throws an exception:

void main() {
    Math.clamp(5, 10, 1);
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: 10 > 1

Notes

Before Java 21 the same was written as Math.max(min, Math.min(max, value)). The integer version takes a long and returns an int, so it also works for squeezing a large long into an int range without overflow.

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.