โ— Shell
clean mode source โ†—

Math.clamp()

Code Comparison

// Clamp value between min and max
int clamped =
    Math.min(Math.max(value, 0), 100);
// or: min and max order confusion
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()

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.

Related Documentation

Proof