Java 21 introduces the new method Math.clamp(value, min, max)
that fits a value within a specified interval. Before Java 21, this
behavior required explicit calls to the Math.min
and Math.max
methods, as in Math.min(max, Math.max(value,
min))
.
If min > max
, Math.clamp
throws an IllegalArgumentException
, indicating an invalid interval. This can
occur if the min
and max
arguments are mistakenly reversed.
Note that Math.clamp
is not a general substitute for Math.min
or Math.max
, but for the combination of both.
If value
is the same as min
or max
, using Math.clamp
is unnecessary and Math.min
or
Math.max
should be used instead.