Library contents

Java Math.clamp

Clamp a value to an inclusive interval.

A simple example

Math.clamp

  1. Start with 8, allowed range 1–5
  2. Do this Keep the value inside the range
  3. Result 5
Eight exceeds the upper limit, so the result is the upper limit.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        System.out.println(Math.clamp(8, 1, 5));
    }
}
Output
5

Syntax

Java syntax
Math.clamp(brightness, low, high)
JDK 21 method signatures (4)
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)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Keep a brightness setting inside the slider range

A display accepts brightness values only within a fixed range. Limit an out-of-range request before sending it to the device, and keep valid settings at their requested levels.

From the programlong brightness = 125L
Result100
Main.java

class Main {
    public static void main(String[] args) throws Exception {
        long brightness = 125L;
        int low = 0;
        int high = 100;
        System.out.println(Math.clamp(brightness, low, high));
    }
}
Output
100

The slider accepts zero through one hundred, so an incoming value of 125 becomes 100.

Advertisements

Set a reading lamp’s brightness

A classroom lamp accepts an intensity from 10 to 90. A saved preference of 4 falls below the allowed interval.

GivenRequested 4 · range 10–90
Worked result10

The lower bound becomes the setting when the request is below the range.

Keep a valid camera zoom

A camera interface allows a zoom level between one and eight. A photographer recalls level five from a preset.

GivenRequested 5 · range 1–8
Worked result5

A request inside the permitted interval passes through.

What to watch for

Keep the lower bound at or below the upper bound. Reversed bounds raise IllegalArgumentException.

Documentation for Math.clamp