Math clamp Bounds Numeric Values

Clamp values into a range with the Java 21 Math.clamp overloads: long-to-int narrowing never overflows, and min greater than max is rejected outright.

JavaData Integrity

Code

snippet
public class VolumeControl {

    public static void main(String[] args) {
        // Math.clamp (Java 21): pulls the value into the range, no hand-written triple ternary
        int[] rawLevels = {-5, 0, 42, 87, 300};

        for (int raw : rawLevels) {
            System.out.println("raw " + raw + " -> " + Math.clamp(raw, 0, 100));
        }

        // safe long -> int narrowing: clamp(long, int, int) returns int directly and never wraps around
        long wide = 4_000_000_000L;
        int narrowed = Math.clamp(wide, 0, 100);
        System.out.println("wide " + wide + " -> " + narrowed);

        // min > max is an illegal argument: clamp throws IllegalArgumentException outright
        try {
            Math.clamp(5, 10, 2);
        } catch (IllegalArgumentException e) {
            System.out.println("bad range: " + e.getClass().getSimpleName());
        }
    }
}

Inside the snippet

The working surface is the class VolumeControl and the function main — everything else is wiring.

Repetition is confined to for (int raw : rawLevels) — the rest of the file is straight-line.

Putting it to use

Output lines are prefixed (raw, wide, bad range:), making each step’s effect easy to spot.

Core lines

int narrowed = Math.clamp(wide, 0, 100);
int[] rawLevels = {-5, 0, 42, 87, 300};
long wide = 4_000_000_000L;

Interactive Tools for This Topic

FAQ

What does Math clamp Bounds Numeric Values print when run?
Running the file directly is enough — expect labeled output lines such as `raw`, `wide`, `bad range:`.