-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathmath-clamp.yaml
More file actions
46 lines (46 loc) · 1.37 KB
/
math-clamp.yaml
File metadata and controls
46 lines (46 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
---
id: 74
slug: "math-clamp"
title: "Math.clamp()"
category: "datetime"
difficulty: "beginner"
jdkVersion: "21"
oldLabel: "Java 8"
modernLabel: "Java 21+"
oldApproach: "Nested min/max"
modernApproach: "Math.clamp()"
oldCode: |-
// Clamp value between min and max
int clamped =
Math.min(Math.max(value, 0), 100);
// or: min and max order confusion
modernCode: |-
int clamped =
Math.clamp(value, 0, 100);
// value constrained to [0, 100]
summary: "Clamp a value between bounds with a single clear call."
explanation: "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."
whyModernWins:
- icon: "📖"
title: "Self-documenting"
desc: "clamp(value, min, max) is unambiguous."
- icon: "🛡️"
title: "Less error-prone"
desc: "No more swapping min/max order by accident."
- icon: "🎯"
title: "All numeric types"
desc: "Works with int, long, float, and double."
support:
state: "available"
description: "Widely available since JDK 21 LTS (Sept 2023)"
prev: "datetime/instant-precision"
next: "datetime/hex-format"
related:
- "datetime/instant-precision"
- "datetime/hex-format"
- "datetime/duration-and-period"
docs:
- title: "Math.clamp()"
href: "https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Math.html#clamp(long,int,int)"