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.
  • Math methods: min/max, abs, pow, sqrt, floor/ceil/round, trig, log
  • Math.addExact/multiplyExact/toIntExact throw on overflow instead of wrapping
  • BigDecimal gives exact decimal arithmetic — construct from String, not double
  • BigInteger handles arbitrarily large integers
  • For randomness use ThreadLocalRandom (or Random with a seed for reproducibility)
Exact arithmetic guards
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-negative

Math 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

Exact money arithmetic
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.

Sources
  • Core Java, Volume I: Fundamentals (13th ed.)Ch. 3.5.4, 3.9 — Mathematical Functions; Big Numbers
  • Learning Java (6th ed.)Ch. 8 — Text and Core Utilities
  • Effective Java (3rd ed.)Item 60