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
| Parameter | Type | Description |
|---|---|---|
| value | long, double, float | The original number. |
| min | int, long, double, float | The lower bound. |
| max | same type as min | The 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
42Decimal 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.25If 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 > 1Notes
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
- Math.max() — Returns the larger of two numbers.
- Math.min() — Returns the smaller of two numbers.
- Math.abs() — Returns the absolute value of a number — the value without a minus sign.
- IllegalArgumentException — Signals that a method received an invalid argument.
In the tutorial
- Operators — Java arithmetic operators, integer division and remainder, compound assignment, increment, comparison and logical operators.