GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • java.evolved
  • ←
  • →

This view

  • Original page
  • New address

GeezerVison is showing javaevolved.dev — Math.clamp() | java.evolved

Home / Date/Time / Math.clamp()
Date/Time Beginner

Math.clamp()

  • 🐛 Report a code issue
  • 🌐 Report a translation issue
  • 💡 Suggest a new pattern

Clamp a value between bounds with a single clear call.

Math
Code Comparison
✕ Java 8
// Clamp value between min and max
int clamped =
    Math.min(Math.max(value, 0), 100);
// or: min and max order confusion
✓ Java 21+
int clamped =
    Math.clamp(value, 0, 100);
// value constrained to [0, 100]
Share 𝕏
See a problem with this code? Let us know.
Why the modern way wins
📖

Self-documenting

clamp(value, min, max) is unambiguous.

🛡️

Less error-prone

No more swapping min/max order by accident.

🎯

All numeric types

Works with int, long, float, and double.

Old Approach
Nested min/max
Modern Approach
Math.clamp()
Since JDK
21
Difficulty
Beginner
JDK Support
Math.clamp()
Available

Widely available since JDK 21 LTS (Sept 2023)

How it works

Math.clamp(value, min, max) constrains a value to the range [min, max]. Clearer than nested Math.min/Math.max and available for int, long, float, and double.

Related Documentation
Math.clamp() ↗
Proof
View proof source ↗
Related patterns
Date/Time Intermediate

Instant with nanosecond precision

Java 8
// Millisecond precision only
long millis =
    System.currentTimeMillis();
// 1708012345678
Java 9+
// Microsecond/nanosecond precision
Instant now = Instant.now();
// 2025-02-15T20:12:25.678901234Z
long nanos = now.getNano();
Hover to see modern ➜
JDK 9+ →
Date/Time Intermediate

HexFormat

Java 8
// Pad to 2 digits, uppercase
String hex = String.format(
    "%02X", byteValue);
// Parse hex string
int val = Integer.parseInt(
    "FF", 16);
Java 17+
var hex = HexFormat.of()
    .withUpperCase();
String s = hex.toHexDigits(
    byteValue);
byte[] bytes =
    hex.parseHex("48656C6C6F");
Hover to see modern ➜
JDK 17+ →
Date/Time Beginner

Duration and Period

Pre-Java 8
// How many days between two dates?
long diff = date2.getTime()
    - date1.getTime();
long days = diff
    / (1000 * 60 * 60 * 24);
// ignores DST, leap seconds
Java 8+
long days = ChronoUnit.DAYS
    .between(date1, date2);
Period period = Period.between(
    date1, date2);
Duration elapsed = Duration.between(
    time1, time2);
Hover to see modern ➜
JDK 8+ →
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.