Math.clamp()
Clamp a value between bounds with a single clear call.
Code Comparison
✕ Java 8
// Clamp value between min and max
int clamped =
Math.min(Math.max(value, 0), 100);
// or: min and max order confusion
✓ Java 21+
int clamped =
Math.clamp(value, 0, 100);
// value constrained to [0, 100]
Why the modern way wins
Self-documenting
clamp(value, min, max) is unambiguous.
Less error-prone
No more swapping min/max order by accident.
All numeric types
Works with int, long, float, and double.
Old Approach
Nested min/max
Modern Approach
Math.clamp()
Since JDK
21
Difficulty
beginner
JDK Support
Math.clamp()
Available
Widely available since JDK 21 LTS (Sept 2023)
How it works
Math.clamp(value, min, max) constrains a value to the range [min, max]. Clearer than nested Math.min/Math.max and available for int, long, float, and double.