Java Math clamp() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 21+

Definition

In Java, Math.clamp(value, min, max) returns value if it is already inside the range, min if it is below, and max if it is above. Math.clamp(120, 0, 100) is 100.

It replaces the classic Math.max(min, Math.min(max, value)) pattern with one readable call, and it also checks that your range makes sense.

A static method of the java.lang.Math class, added in Java 21 (JDK 21). Call it on the class name, as in Math.clamp(...). No import is needed, because classes in java.lang are always visible. Requires Java 21 or newer.

Syntax

Pass the value first, then the lower and upper limits (both inclusive).

Java
int volume = Math.clamp(120, 0, 100);          // 100
double temp = Math.clamp(26.5, 16.0, 25.0);    // 25.0
int safe = Math.clamp(bigLong, 0, 1000);       // long in, int out
Math.clamp(5, 10, 1);                          // IllegalArgumentException
CallWhat it does
Math.clamp(-10, 0, 100)Below the range: returns 0.
Math.clamp(35, 0, 100)Inside the range: returns 35.
Math.clamp(5_000_000_000L, 0, Integer.MAX_VALUE)A long squeezed into int range: returns 2147483647 as an int.
Math.clamp(x, 0.0, 1.0)Keep a fraction between 0.0 and 1.0.

The int version takes a long value with int limits, so the result always fits in an int without a cast. Passing three ints also selects it.

Library declarations
Java
// java.lang.Math (Java 21+)
public static int clamp(long value, int min, int max)
public static long clamp(long value, long min, long max)
public static double clamp(double value, double min, double max)
public static float clamp(float value, float min, float max)

Parameters

ParameterDescription
valueThe number to limit.
minThe lowest allowed result (inclusive).
maxThe highest allowed result (inclusive). Must not be less than min.

Return Value

Return ValueDescription
int / long / float / doublevalue limited to the range min..max.
Throws IllegalArgumentExceptionIf min > max; for float/double also if min or max is NaN, or min is 0.0 and max is -0.0.

Compare with Similar Methods

Ways to keep numbers inside limits:

MethodHow it differs
max(lo, x)Lower limit only.
min(hi, x)Upper limit only.
Math.max(lo, Math.min(hi, x))Works on Java 8; no check that lo <= hi.
toIntExact(v)Throws for an out-of-range long instead of capping it.

Java Examples

Example 1 — Keep a Volume Between 0 and 100

User requests go outside the allowed range; clamp pulls them back in. This example needs Java 21 or newer.

Java
public class MathClampVolume {
    public static void main(String[] args) {
        int[] requests = {-10, 35, 120};
        for (int r : requests) {
            int volume = Math.clamp(r, 0, 100);
            System.out.println("requested " + r + " -> volume " + volume);
        }
    }
}

How It Works

  1. Too low. -10 is below the minimum, so clamp returns the lower limit 0.
  2. Already fine. 35 lies inside 0..100, so it is returned unchanged.
  3. Too high, and still an int. 120 becomes 100; because the limits are ints, the clamp(long, int, int) overload runs and returns an int with no cast needed.

Example 2 — Thermostat Limits and a NaN Reading

Clamp decimal temperatures and fractions. Java 21+.

Java
public class MathClampThermostat {
    public static void main(String[] args) {
        System.out.println("Set 26.5 -> " + Math.clamp(26.5, 16.0, 25.0));
        System.out.println("Set 12.0 -> " + Math.clamp(12.0, 16.0, 25.0));
        System.out.println("Fraction 0.42 -> " + Math.clamp(0.42, 0.0, 1.0));
        System.out.println("Broken sensor -> " + Math.clamp(Double.NaN, 16.0, 25.0));
    }
}

How It Works

  1. Upper and lower limit. 26.5 is capped at 25.0 and 12.0 is raised to 16.0, the coolest and warmest allowed settings.
  2. In range stays exact. 0.42 is between 0.0 and 1.0, so the same double comes back.
  3. NaN passes through. A missing reading (NaN) is not inside or outside the range, so clamp returns NaN rather than inventing a temperature.

Example 3 — Squeeze a long into int Range, and a Bad Range

Turn a large file size into a safe int, then pass limits in the wrong order. Java 21+.

Java
public class MathClampErrors {
    public static void main(String[] args) {
        long bytes = 5_000_000_000L;
        int capped = Math.clamp(bytes, 0, Integer.MAX_VALUE);
        System.out.println("Capped to int: " + capped);
        try {
            Math.clamp(50, 100, 0);
        } catch (IllegalArgumentException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

How It Works

  1. No overflow. 5000000000 does not fit in an int; a plain (int) cast would wrap to a wrong value, but clamp returns the largest int instead.
  2. Limits checked first. In Math.clamp(50, 100, 0) the minimum 100 is larger than the maximum 0, which is a programming mistake.
  3. Clear message. The IllegalArgumentException text 100 > 0 shows exactly which limits were swapped.

Frequently Asked Questions

It limits a value to a range: it returns min if the value is smaller, max if the value is larger, and the value itself otherwise.
Java 21. On older versions use Math.max(min, Math.min(max, value)).
It throws IllegalArgumentException when min is greater than max. The float and double versions also throw when min or max is NaN, or when min is 0.0 and max is -0.0.
If the value is NaN, the double and float versions return NaN. Only NaN limits cause an exception.
Because the result is always between two int limits, it always fits in an int. This makes clamp a safe way to convert a long to an int without overflow.

Next: copySign()

Return the first number with the sign of the second number.

copySign() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful