java.lang.Math is a final class of static methods and constants (PI, E, TAU from Java 19 — use 2 * Math.PI on Java 17). You never construct it. The package is imported by default.
BigDecimal), integer sets/streams (use Integer.max or collections), cryptography or tokens (SecureRandom), statistics libraries you should not reinvent.StrictMath is the same idea with a stricter reproducibility spec. Use it only if you must match bit-for-bit results across JVMs. Ordinary apps use Math.Math.clamp. Before that, write Math.min(hi, Math.max(lo, x)).Mental model: double is IEEE-754 binary floating point, not “decimal with extra digits.” 0.1 + 0.2 == 0.3 is false. Compare with an epsilon, or do not use binary floats for that domain.
Overloaded for int, long, float, double. Math.max(NaN, x) is NaN for floating types. For streams of many values use IntStream.max, not a handwritten loop unless you must.
int m = Math.min(10, 5); // 5
Removes the sign. Return type matches the argument for primitive overloads. Trap: Math.abs(Integer.MIN_VALUE) is still Integer.MIN_VALUE (overflow). Same for Long.MIN_VALUE. Java 15+ has absExact which throws ArithmeticException.
int val = Math.abs(-10); // 10 int boom = Math.abs(Integer.MIN_VALUE); // still MIN_VALUE
pow and sqrt return double. Prefer Math.hypot(x, y) over sqrt(x*x + y*y) to reduce overflow. Math.pow(2, 3) is 8.0, not 8.
double p = Math.pow(2, 3); // 8.0 double s = Math.sqrt(16); // 4.0 double c = Math.cbrt(27); // 3.0
ceil / floor / rint return double (the mathematical integer as a double). round(float) returns int; round(double) returns long. Ties for round go toward +∞ (0.5 → 1, -0.5 → 0). rint ties to even.
Math.ceil(2.3); // 3.0 Math.floor(2.7); // 2.0 Math.round(2.5); // 3L Math.round(-2.5); // -2L
Math.random() is [0.0, 1.0) from a shared Random. Fine for toys. Not for security. Not for uncorrelated streams in many threads (contention + poor practice). Prefer ThreadLocalRandom.current().nextInt(n) for simulations and SecureRandom for tokens.
int die = ThreadLocalRandom.current().nextInt(1, 7); // 1..6 int oldSchool = (int) (Math.random() * 6) + 1;
Use these when you care about IEEE details: sign of zero, the next representable double, or scaling by units in the last place. signum(0.0) is 0.0; signum(-0.0) is -0.0.
Math.addExact, subtractExact, multiplyExact, incrementExact, toIntExact throw ArithmeticException on overflow. Use them for money-as-integer-cents and sizes that must not wrap silently.
int sum = Math.addExact(a, b); int narrowed = Math.toIntExact(longValue);
int bounded = Math.clamp(value, 0, 100); double d = Math.clamp(x, 0.0, 1.0);
On Java 17: Math.min(100, Math.max(0, value)). Confirm lo <= hi yourself; Java 21 clamp throws if the range is empty.
| Value | How you get it | What to remember |
|---|---|---|
| NaN | 0.0/0.0, sqrt(-1) | NaN != NaN. Use Double.isNaN. Any relational compare with NaN is false. |
| ±Infinity | 1.0/0.0 | Double.isInfinite. Overflow of range, not of integer wrap. |
| -0.0 | signed zero | -0.0 == 0.0 is true; Double.compare treats them as different; 1.0/-0.0 is −∞. |
// Incorrect
if (sum == 0.3) { }
// Correct — domain-specific tolerance, not a magic universal constant
if (Math.abs(sum - 0.3) < 1e-9) { }
// Correct — total order including NaN
int cmp = Double.compare(a, b);
Float/Double.compare and their compareTo treat NaN as greater than everything and distinguish −0.0 from 0.0. == does not. Pick one rule and use it in equals/compareTo consistently (or do not use floats as map keys).
int/long wrap in two’s complement. Integer.MAX_VALUE + 1 is MIN_VALUE. Silent wrap is a security and money bug.addExact or a wider type, then narrow with toIntExact.Math.pow is a double. (int) Math.pow(10, 8) can be off for larger exponents. Prefer integer loops, BigInteger, or a known table.BigDecimal with a MathContext or explicit scale + RoundingMode. Never new BigDecimal(0.1) — that captures the double error. Use new BigDecimal("0.1") or BigDecimal.valueOf(0.1) only when you mean the double’s value.BigDecimal price = new BigDecimal("19.99");
BigDecimal tax = price.multiply(new BigDecimal("0.18"), new MathContext(10, RoundingMode.HALF_UP));
| Need | API | Avoid |
|---|---|---|
| Die rolls, shuffles in one thread | ThreadLocalRandom or a local Random | Seeding with currentTimeMillis in a tight loop |
| Many threads, simulations | ThreadLocalRandom or SplittableRandom | One shared Random (lock) or Math.random() |
| Tokens, reset codes, keys | SecureRandom | Math.random, Random, time-based seeds |
| Angles | radians. toRadians / toDegrees | Feeding degrees into sin |
| log10 of integers | Math.log10 | Assuming it is exact for powers of ten |
Trig and exp/log follow IEEE; they are not symbolic algebra. sin(Math.PI) is a tiny non-zero, not 0.0.
| Function | Returns | Example / trap |
|---|---|---|
pow(a, b) | double | pow(2, 3) → 8.0 |
sqrt(a) | double | sqrt(−1) → NaN |
cbrt(a) | double | cbrt(27) → 3.0 |
hypot(x, y) | double | Safer than sqrt(x*x+y*y) |
ceil(a) | double | ceil(4.2) → 5.0 |
floor(a) | double | floor(4.9) → 4.0 |
round(a) | int / long | round(2.5) → 3; half away from zero toward +∞ |
abs(a) | same primitive | abs(MIN_VALUE) overflows; prefer absExact |
max / min | same | NaN in, NaN out (float/double) |
addExact / … | int / long | Throws on overflow |
clamp (21) | same | Throws if min > max |
random() | double | [0.0, 1.0). Not for security |
Math.ceil(5.4) + Math.ceil(4.5)?Math.sqrt(Math.ceil(15.3))Math.abs(a + b) / Math.hypot(a, b) (hypot is the production form; Math.sqrt(a * a + b * b) is the school form).Math.random()double in [0.0, 1.0).Math.abs(Integer.MIN_VALUE)?Integer.MIN_VALUE. Use Math.absExact if that must be an error.new BigDecimal(0.1) wrong for money?== unless you mean bit equality (and you usually do not).*Exact when wrap is a defect.Math.abs(MIN_VALUE) is a loaded gun. Know it.Math.random() is not a security API and is a poor concurrent RNG.hypot, addExact, clamp (21) / min-max (17) over ad-hoc formulas you have not tested at the edges.double keys in a HashMap unless you enjoy NaN and −0.0 bugs.~ Good luck with your revision! ~