Language Fundamentals
Numbers, Math & Big Numbers
The
Math class covers everyday numeric work; Math.*Exact methods turn silent overflow into exceptions; and BigInteger/BigDecimal trade speed for unlimited precision and exact decimal arithmetic.Mathmethods:min/max,abs,pow,sqrt,floor/ceil/round, trig,logMath.addExact/multiplyExact/toIntExactthrow on overflow instead of wrappingBigDecimalgives exact decimal arithmetic — construct from String, not doubleBigIntegerhandles arbitrarily large integers- For randomness use
ThreadLocalRandom(orRandomwith a seed for reproducibility)
long ns = Math.multiplyExact(seconds, 1_000_000_000L); // throws on overflow
int idx = Math.toIntExact(longValue); // safe narrowing
int wrapped = Math.floorMod(hash, buckets); // always non-negativeMath methods are static — with import static java.lang.Math.* you can write sqrt(pow(x, 2) + pow(y, 2)). StrictMath guarantees bit-identical results across platforms; Math may use faster hardware intrinsics.
BigInteger and BigDecimal
BigDecimal price = new BigDecimal("19.99"); // from String — exact
BigDecimal qty = BigDecimal.valueOf(3);
BigDecimal total = price.multiply(qty); // 59.97, exactly
BigDecimal each = total.divide(BigDecimal.valueOf(7), 2, RoundingMode.HALF_UP);Big numbers are immutable objects without operator support — a.add(b.multiply(c)) instead of a + b * c — and orders of magnitude slower than primitives. Use them when correctness demands it (money, cryptography, combinatorics), not by default. Effective Java Item 60: float/double are for scientific measurement, not exact quantities.