Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

2 Comments
Oldest
Newest