Math Clamp Bounds Range Values
Math.clamp bounds a value in one call, replaces nested max-min chains, and rejects an inverted range with IllegalArgumentException instead of guessing.
Code
import java.util.List;
public class RangeGuard {
public static void main(String[] args) {
List<Integer> readings = List.of(-12, 3, 55, 120);
for (int reading : readings) {
// the manual guard nests max inside min; clamp is one call
int manual = Math.max(0, Math.min(reading, 100));
int clamped = Math.clamp(reading, 0, 100);
System.out.println(reading + " -> " + clamped + " (manual " + manual + ")");
}
// narrowing a long into a small range uses the long/int overload
System.out.println(Math.clamp(300L, 0, 255));
System.out.println(Math.clamp(-1.5, 0.0, 1.0));
// min > max throws IllegalArgumentException; inverted ranges are never accepted silently
try {
Math.clamp(5, 10, 2);
} catch (IllegalArgumentException e) {
System.out.println("invalid range rejected");
}
}
}What the demo bounds
Four readings, -12, 3, 55 and 120, pass through Math.clamp(value, 0, 100) and come out 0, 3, 55 and 100. Beside each, the manual Math.max(0, Math.min(reading, 100)) produces the identical number, showing clamp replaces the nested chain one-for-one.
The overloads cover the widening cases: clamp(300L, 0, 255) narrows a long to 255 and clamp(-1.5, 0.0, 1.0) bounds a double to 0.0. An inverted range is not tolerated: clamp(5, 10, 2) throws IllegalArgumentException, printed as invalid range rejected.
Practical notes
- Clamping applies to values; the bounds themselves are validated separately.
- The exception names min and max, so bad call sites are easy to find.
Interactive Tools for This Topic
CSS clamp() GeneratorGenerate responsive clamp(MIN, PREFERRED, MAX) values with automatic calc() wrapping for expressions.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- When does Math.clamp throw?
- Only when min > max: clamp(5, 10, 2) throws IllegalArgumentException because the range itself is inverted; out-of-range values are clamped, never rejected.
Report a problem with this exampleOpens a pre-filled issue on GitHub.