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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.