Search code examples
javarangemaxminclamp

Java - limit number between min and max


I want to return the number as long as it falls within a limit, else return the maximum or minimum value of the limit. I can do this with a combination of Math.min and Math.max.

public int limit(int value) {
    return Math.max(0, Math.min(value, 10));
}

I'm wondering if there's an existing limit or range function I'm overlooking.
3rd party libraries welcome if they are pretty common (eg: Commons or Guava)


Solution

  • There is new Math.clamp method (with multiple overloads) added in Java 21 to conveniently clamp the numeric value between the specified minimum and maximum values:

    int valueToClamp = 0;
    
    System.out.println(Math.clamp(valueToClamp, 1, 10)); // 1
    

    public static int clamp(long value, int min, int max)

    • value - value to clamp
    • min - minimal allowed value
    • max - maximal allowed value