1. Overview

A clamp function restricts a value to within a range. It ensures a given value doesn’t fall outside specific lower and upper boundaries.

In this tutorial, we’ll explore with examples how to implement the clamp function in Java.

2. Clamp Function Before Java 21

Prior to Java 21, Java didn’t have an inbuilt function to clamp a value. We need to write our clamp function ourselves.

A clamp function specifies a range of values. Values below the minimum are set to the minimum. Values above the maximum are set to the maximum. Also, values within the range return themselves.

2.1. Using Method Overloading

We can use method overloading to implement the clamp function for different data types.

Let’s create a Clamp class and add a clamp() method that returns an integer:

class Clamp {  
    int clamp(int value, int min, int max) {
        return Math.max(min, Math.min(max, value));
    }   
}

Here, we create a clamp() method that accepts the value, lower, and upper boundary as arguments. Furthermore, we use the Math class to set the minimum and the maximum values. Finally, we return the value if it’s in the set range and return the minimum or the maximum if the value isn’t in the range.

Let’s write a unit test for the clamp() method:

@Test
void givenValueOutsideRange_whenClamp_thenReturnLowerValue() {
    Clamp clampValue = new Clamp();
    assertEquals(15, clampValue.clamp(10, 15, 35));
}

Here, we create an instance of Clamp and invoke clamp() on it. The value is set to 10,  the minimum value is set to 15, and the maximum to 35. Since the value isn’t within range, the method returns the minimum.

Here’s a test for value within the range:

assertEquals(20, clampValue.clamp(20, 15, 35));

Since the input value falls within the range, the clamp() method returns this value.

Finally, let’s see a test for a value above the maximum value:

assertEquals(35, clampValue.clamp(50, 15, 35));

Here, the input value exceeds the maximum boundary. Hence, the clamp() method returns the maximum value.

Furthermore, let’s implement a clamp function for double data type by overloading the clamp() method:

double clamp(double value, double min, double max) {
    return Math.max(min, Math.min(max, value));
}

Here, we overload the clamp() with double data type. Additionally, the method returns a double.

2.2. Using Generics

Furthermore, we can use generics to make the clamp() method more flexible and work with different data types:

static <T extends Comparable<T>> T clamp(T value, T min, T max) {
    if (value.compareTo(min) < 0) {
        return min;
    } else if (value.compareTo(max) > 0) {
        return max;
    } else {
        return value;
    }
}

The method above takes three arguments of generic type T. T also implements a Comparable interface. However, this method could be expensive. If the minimum and the maximum are primitive types, Java will automatically box them into equivalent objects because primitive types cannot implement Comparable.

Let’s write a unit test for the generic method:

@Test
void givenFloatValueWithinRange_whenClamp_thenReturnValue() {
    Clamp clampValue = new Clamp();
    assertEquals(16.2f, clampValue.clamp(16.2f, 15f, 35.3f));
}

The method accepts a float type, but while computing the value, it boxes float to Float and later unboxes the return value from Float to float. Therefore, we have two box operations and one unbox operation.

Method overloading is recommended to avoid boxing/unboxing operations.

3. Clamp Function After Java 21

Java 21, which is still in the experimental stage, introduces the clamp() method in the Math class. This method makes it easy to clamp a value without writing our own method.

Here’s an example that uses the clamp() in Java 21:

@Test
void givenValueWithinRange_whenClamp_thenReturnValue() {
    assertEquals(20, Math.clamp(20, 17, 98));
}

In the code above, we invoke the clamp() method and set the minimum and maximum values. The code returns the value because it’s within the minimum and maximum.

Notably, the clamp() method supports different data types. Therefore, there’s no need for explicit implementation for different data types.

4. Conclusion

In this article, we learned three different methods to implement the clamp function in Java. We saw how to write a clamp() method before Java 21 introduced the clamp() method in the standard library.

As always, the source code for the examples is available over on GitHub.

Course – LS (cat=Java)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
2 Comments
Oldest
Newest
Inline Feedbacks
View all comments
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.