The Math Class

java.lang.Math holds the numeric functions that Java does not build into operators: powers and roots, rounding, floor division, overflow-checked arithmetic and more. This page runs each group of methods and spends most of its time on the edge cases, such as halfway values, NaN, negative zero and integer overflow, where the results surprise people.

Contents

What java.lang.Math provides

The operators +, -, *, / and % cover basic arithmetic. Everything else numeric lives in java.lang.Math: absolute values, powers and roots, logarithms, trigonometry, rounding, division that rounds down, and arithmetic that reports overflow instead of hiding it. The class is final, has a private constructor, and every member is static, so you call Math.sqrt(2) without creating anything.

The class has grown in almost every release. The table lists the groups of methods with the version that added the newer ones, so you can tell what is available on the JDK you target.

Method groups in Math and related classes
GroupExamplesSinceBest for
Basic functionsabs, max, pow, sqrt, sin, log1.0Everyday formulas in double
Roundingfloor, ceil, round, rint1.0Turning a double into a whole number
Floor division and exact arithmeticfloorDiv, floorMod, addExact, toIntExact8Negative operands and overflow detection
Wide and fused operationsmultiplyFull, multiplyHigh, fma9Products that need more than 64 bits or one rounding
Newer helpersabsExact (15), ceilDiv (18), clamp (21)15 to 21Replacing hand-written versions of the same checks
Reproducible resultsStrictMath1.3Bit-identical results on every platform
Random numbersRandom, ThreadLocalRandom (7), RandomGenerator (17)1.0 to 17Simulations, tests and games, not security

The examples below print each group, and most of the space goes to the edge cases: negative numbers, halfway values, infinity, NaN and overflow. Those are where the methods behave differently from what people expect.

Everyday functions

Each line uses an input whose correct answer is easy to check by hand, so any surprise in the output is a real property of floating point.

Java
public class MathBasics {

    public static void main(String[] args) {
        System.out.println("abs(-7) = " + Math.abs(-7));
        System.out.println("max(3, 9) = " + Math.max(3, 9));
        System.out.println("min(2.5, -1) = " + Math.min(2.5, -1));
        System.out.println("clamp(150, 0, 100) = " + Math.clamp(150, 0, 100));     // Java 21
        System.out.println("pow(2, 10) = " + Math.pow(2, 10) + ", sqrt(2) = " + Math.sqrt(2));
        System.out.println("cbrt(27) = " + Math.cbrt(27) + ", hypot(3, 4) = " + Math.hypot(3, 4));
        System.out.println("log(e) = " + Math.log(Math.E) + ", log10(1000) = " + Math.log10(1000));
        System.out.println("sin(PI/6) = " + Math.sin(Math.PI / 6) + "  (not exactly 0.5)");
        System.out.println("StrictMath.sin(PI/6) = " + StrictMath.sin(Math.PI / 6));
        System.out.println("toDegrees(PI) = " + Math.toDegrees(Math.PI)
                + ", sin(toRadians(30)) = " + Math.sin(Math.toRadians(30)));
        System.out.println("signum(-3.2) = " + Math.signum(-3.2));
    }
}

Output:

Output
abs(-7) = 7
max(3, 9) = 9
min(2.5, -1) = -1.0
clamp(150, 0, 100) = 100
pow(2, 10) = 1024.0, sqrt(2) = 1.4142135623730951
cbrt(27) = 3.0, hypot(3, 4) = 5.0
log(e) = 1.0, log10(1000) = 3.0
sin(PI/6) = 0.49999999999999994  (not exactly 0.5)
StrictMath.sin(PI/6) = 0.49999999999999994
toDegrees(PI) = 180.0, sin(toRadians(30)) = 0.49999999999999994
signum(-3.2) = -1.0
  • The Math.clamp(150, 0, 100) call returned 100. It is the Java 21 replacement for the common Math.max(min, Math.min(max, value)) idiom, and it throws if min is greater than max instead of returning nonsense.
  • The pow, sqrt, log and trigonometric methods take and return double. Even pow(2, 10) printed 1024.0, so cast the result if you need an int.
  • The value sin(PI/6) printed 0.49999999999999994, not 0.5. The constant Math.PI is the closest double to pi, not pi itself, so the input was already slightly off before sin ran.
  • Trigonometric methods work in radians. The line with toRadians(30) gave the same 0.49999999999999994, because converting 30 degrees produces the same rounded value of pi divided by 6.
  • The StrictMath.sin result matched Math.sin here. The two classes are allowed to differ in the last bit, which the section on StrictMath below explains.

Rounding and integer division

The table uses halfway values and negative numbers, which are the inputs where the four rounding methods disagree. The second half compares Java's integer division with the floor versions.

Java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class Rounding {

    public static void main(String[] args) {
        double[] values = {2.5, 3.5, -2.5, 2.4, -2.6};
        System.out.printf("%6s %7s %7s %7s %7s%n", "x", "floor", "ceil", "round", "rint");
        for (double v : values) {
            System.out.printf("%6.1f %7.1f %7.1f %7d %7.1f%n",
                    v, Math.floor(v), Math.ceil(v), Math.round(v), Math.rint(v));
        }

        // Rounding to 2 decimal places with doubles is approximate
        double price = 1.005;
        double rounded = Math.round(price * 100) / 100.0;
        System.out.println("Math.round(1.005 * 100) / 100.0 = " + rounded);
        System.out.println("because 1.005 is really " + new BigDecimal(price));
        System.out.println("BigDecimal(\"1.005\").setScale(2, HALF_UP) = "
                + new BigDecimal("1.005").setScale(2, RoundingMode.HALF_UP));
        System.out.println("Math.round(0.49999999999999994) = " + Math.round(0.49999999999999994)
                + ", Math.round(-0.5) = " + Math.round(-0.5));

        // Integer division variants
        System.out.println("-7 / 2 = " + (-7 / 2) + ", floorDiv(-7, 2) = " + Math.floorDiv(-7, 2));
        System.out.println("-7 % 2 = " + (-7 % 2) + ", floorMod(-7, 2) = " + Math.floorMod(-7, 2));
        System.out.println("ceilDiv(7, 2) = " + Math.ceilDiv(7, 2) + "  (Java 18)");
    }
}

Output:

Output
x   floor    ceil   round    rint
   2.5     2.0     3.0       3     2.0
   3.5     3.0     4.0       4     4.0
  -2.5    -3.0    -2.0      -2    -2.0
   2.4     2.0     3.0       2     2.0
  -2.6    -3.0    -2.0      -3    -3.0
Math.round(1.005 * 100) / 100.0 = 1.0
because 1.005 is really 1.00499999999999989341858963598497211933135986328125
BigDecimal("1.005").setScale(2, HALF_UP) = 1.01
Math.round(0.49999999999999994) = 0, Math.round(-0.5) = 0
-7 / 2 = -3, floorDiv(-7, 2) = -4
-7 % 2 = -1, floorMod(-7, 2) = 1
ceilDiv(7, 2) = 4  (Java 18)
  • The floor method rounds toward negative infinity and ceil toward positive infinity. For -2.5 that gave -3.0 and -2.0, the opposite of what "round down" and "round up" suggest if you think in terms of size.
  • The round method sends ties toward positive infinity, so 2.5 became 3 but -2.5 became -2, and -0.5 became 0. It returns a long for a double argument and an int for a float.
  • The rint method rounds ties to the even neighbor (2.5 to 2.0, 3.5 to 4.0) and returns a double. This "banker's rounding" does not drift upward when you round many halfway values.
  • The value 0.49999999999999994 rounded to 0. Java 6 and earlier returned 1 for it, because the old formula added 0.5 first and that sum rounded to exactly 1.0. The bug was fixed in Java 7 (JDK-6430675).
  • Rounding to cents with Math.round(x * 100) / 100.0 turned 1.005 into 1.0. The BigDecimal line shows why: the stored double is 1.00499999999999989..., slightly below the tie. A BigDecimal built from the string "1.005" rounded correctly to 1.01, as covered in BigDecimal and BigInteger.
  • Integer / truncates toward zero, so -7 / 2 is -3, and % takes the sign of the dividend, giving -1. The floor versions gave -4 and 1, which is what you want for bucketing, clock arithmetic and array indexes.

Infinity, NaN and negative zero

Integer arithmetic throws on division by zero. Floating-point arithmetic follows IEEE 754 instead and returns special values, which then flow silently through every later calculation.

Java
public class FloatEdges {

    public static void main(String[] args) {
        // Division by zero: integers throw, floating point does not
        try {
            System.out.println(1 / zero());
        } catch (ArithmeticException e) {
            System.out.println("1 / 0 (int):          ArithmeticException: " + e.getMessage());
        }
        System.out.println("1.0 / 0.0:            " + 1.0 / 0.0);
        System.out.println("-1.0 / 0.0:           " + -1.0 / 0.0);
        System.out.println("0.0 / 0.0:            " + 0.0 / 0.0);
        System.out.println("Math.sqrt(-1):        " + Math.sqrt(-1));
        System.out.println("Math.log(0):          " + Math.log(0));

        // NaN is not equal to anything, itself included
        double nan = Double.NaN;
        System.out.println("NaN == NaN:           " + (nan == nan) + ", Double.isNaN: "
                + Double.isNaN(nan) + ", Double.valueOf(NaN).equals(NaN): "
                + Double.valueOf(nan).equals(nan));
        System.out.println("Math.max(3, NaN):     " + Math.max(3, nan));

        // Negative zero
        System.out.println("0.0 == -0.0:          " + (0.0 == -0.0) + ", Double.compare: "
                + Double.compare(0.0, -0.0));
        System.out.println("Math.min(0.0, -0.0):  " + Math.min(0.0, -0.0));
        System.out.println("1 / -0.0:             " + 1 / -0.0);

        // Some exact special cases from the Javadoc
        System.out.println("Math.pow(0, 0):       " + Math.pow(0, 0));
        System.out.println("Math.pow(-8, 1.0/3):  " + Math.pow(-8, 1.0 / 3)
                + ", Math.cbrt(-8): " + Math.cbrt(-8));
        System.out.println("Math.ulp(1.0):        " + Math.ulp(1.0)
                + ", Math.ulp(1e16): " + Math.ulp(1e16));
    }

    static int zero() {
        return 0;
    }
}

Output:

Output
1 / 0 (int):          ArithmeticException: / by zero
1.0 / 0.0:            Infinity
-1.0 / 0.0:           -Infinity
0.0 / 0.0:            NaN
Math.sqrt(-1):        NaN
Math.log(0):          -Infinity
NaN == NaN:           false, Double.isNaN: true, Double.valueOf(NaN).equals(NaN): true
Math.max(3, NaN):     NaN
0.0 == -0.0:          true, Double.compare: 1
Math.min(0.0, -0.0):  -0.0
1 / -0.0:             -Infinity
Math.pow(0, 0):       1.0
Math.pow(-8, 1.0/3):  NaN, Math.cbrt(-8): -2.0
Math.ulp(1.0):        2.220446049250313E-16, Math.ulp(1e16): 2.0
  • The integer division threw ArithmeticException with the message "/ by zero". The double divisions gave Infinity, -Infinity and NaN, and sqrt(-1) and log(0) also returned special values instead of failing.
  • The comparison NaN == NaN printed false, because IEEE 754 defines NaN as unequal to everything. Test with Double.isNaN. The boxed Double.equals returned true, so NaN keys still work in a HashMap, as described in equals and hashCode.
  • The call Math.max(3, NaN) returned NaN. Any NaN input poisons the result, so one bad value in a data set makes its maximum NaN rather than being skipped.
  • Positive and negative zero compare equal with ==, but Double.compare returned 1, ordering 0.0 above -0.0. Math.min also treats -0.0 as smaller, and dividing 1 by -0.0 gave -Infinity, so the sign does change later results.
  • The call pow(-8, 1.0/3) returned NaN because 1.0/3 is not exactly one third, so the result would be a complex number. The dedicated cbrt method returned -2.0.
  • The value Math.ulp(1e16) is 2.0, which means doubles near 1016 are spaced two apart. Above about 9 x 1015 a double can no longer hold every whole number, which is why money and IDs belong in long or BigDecimal.

Overflow and exact arithmetic

An int holds values up to 2,147,483,647, and going past that wraps around without any error. The exact methods added in Java 8 throw instead, and a few others give you the bits that would otherwise be lost.

Java
public class ExactArithmetic {

    public static void main(String[] args) {
        int big = 2000000000;
        System.out.println("big + big =              " + (big + big) + "  (silent overflow)");
        try {
            Math.addExact(big, big);
        } catch (ArithmeticException e) {
            System.out.println("addExact(big, big):      ArithmeticException: " + e.getMessage());
        }
        try {
            Math.toIntExact(3000000000L);
        } catch (ArithmeticException e) {
            System.out.println("toIntExact(3e9):         ArithmeticException: " + e.getMessage());
        }
        System.out.println("multiplyFull(1e5, 1e5) = " + Math.multiplyFull(100000, 100000));
        System.out.println("multiplyHigh(Long.MAX, 4) = " + Math.multiplyHigh(Long.MAX_VALUE, 4)
                + "  (the upper 64 bits of the 128-bit product)");

        // abs(MIN_VALUE) is still negative: there is no positive int of that size
        System.out.println("Math.abs(Integer.MIN_VALUE) = " + Math.abs(Integer.MIN_VALUE));
        try {
            Math.absExact(Integer.MIN_VALUE);                     // Java 15
        } catch (ArithmeticException e) {
            System.out.println("Math.absExact(MIN_VALUE):  ArithmeticException");
        }
        // ...which breaks the classic "random bucket" formula
        int unlucky = Integer.MIN_VALUE;                          // a possible hashCode()
        System.out.println("Math.abs(h) % 10 = " + Math.abs(unlucky) % 10
                + ", Math.floorMod(h, 10) = " + Math.floorMod(unlucky, 10));

        // fma: a * b + c with a single rounding (Java 9)
        double a = 0.1;
        double b = 10;
        double c = -1;
        System.out.println("0.1 * 10 - 1 = " + (a * b + c) + ", Math.fma = " + Math.fma(a, b, c));
    }
}

Output:

Output
big + big =              -294967296  (silent overflow)
addExact(big, big):      ArithmeticException: integer overflow
toIntExact(3e9):         ArithmeticException: integer overflow
multiplyFull(1e5, 1e5) = 10000000000
multiplyHigh(Long.MAX, 4) = 1  (the upper 64 bits of the 128-bit product)
Math.abs(Integer.MIN_VALUE) = -2147483648
Math.absExact(MIN_VALUE):  ArithmeticException
Math.abs(h) % 10 = -8, Math.floorMod(h, 10) = 2
0.1 * 10 - 1 = 0.0, Math.fma = 5.551115123125783E-17
  • Adding 2,000,000,000 to itself printed -294967296. The true sum, 4,000,000,000, is 232 minus 294,967,296, so the result is the true value with 232 subtracted. The addExact call threw "integer overflow" for the same input.
  • The toIntExact method is the checked version of an (int) cast from long. It threw for 3,000,000,000, where a plain cast would have kept the low 32 bits, as shown in type casting.
  • The multiplyFull call returned 10,000,000,000 as a long, where 100000 * 100000 in int would overflow. The multiplyHigh call returned 1, the top half of the 128-bit product of Long.MAX_VALUE and 4.
  • The call Math.abs(Integer.MIN_VALUE) returned the same negative number, because +2,147,483,648 does not fit in an int. The absExact method from Java 15 throws instead.
  • This bites hash-based code. A hashCode() can be Integer.MIN_VALUE, and then Math.abs(h) % 10 gave the invalid bucket -8. Using Math.floorMod(h, 10) gave 2, which is always in the range 0 to 9.
  • The expression 0.1 * 10 - 1 printed 0.0, while Math.fma printed 5.55E-17. The product 0.1 x 10 rounds to exactly 1.0 and hides the error in 0.1. The fused multiply-add rounds only once, at the end, so it keeps that error.

Random numbers

Java has several generators, and the right one depends on whether you need repeatability, speed across threads, or a specific algorithm. Because random values change on every run, the program prints checks on them instead of the values, except where a fixed seed makes them repeatable.

Java
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.random.RandomGenerator;
import java.util.random.RandomGeneratorFactory;

public class RandomNumbers {

    public static void main(String[] args) {
        // A seeded Random repeats the same sequence: good for tests and simulations
        Random a = new Random(42);
        Random b = new Random(42);
        System.out.println("seed 42, two generators: " + a.nextInt(1, 7) + a.nextInt(1, 7)
                + a.nextInt(1, 7) + " and " + b.nextInt(1, 7) + b.nextInt(1, 7) + b.nextInt(1, 7));

        // Math.random() is a shared Random: fine for quick use, a contention point in threads
        double r = Math.random();
        System.out.println("Math.random() in [0, 1): " + (r >= 0 && r < 1));

        // ThreadLocalRandom: one generator per thread, the default in concurrent code
        int roll = ThreadLocalRandom.current().nextInt(1, 7);
        System.out.println("ThreadLocalRandom roll in [1, 6]: " + (roll >= 1 && roll <= 6));

        // Java 17: algorithms chosen by name, all behind the RandomGenerator interface
        long count = RandomGeneratorFactory.all().count();
        RandomGenerator g = RandomGenerator.of("L64X128MixRandom");
        System.out.println("RandomGenerator algorithms in this JDK: " + count
                + "; default is " + RandomGenerator.getDefault().getClass().getSimpleName());
        RandomGeneratorFactory<RandomGenerator> f = RandomGeneratorFactory.of("L64X128MixRandom");
        System.out.println("L64X128MixRandom: state bits " + f.stateBits() + ", splittable "
                + f.isSplittable() + ", next in [0, 100): " + (g.nextInt(100) < 100));

        // Distribution check: nextInt(3) is uniform, the counts of 3 million rolls are close
        Random seeded = new Random(7);
        int[] counts = new int[3];
        for (int i = 0; i < 3000000; i++) {
            counts[seeded.nextInt(3)]++;
        }
        int min = Math.min(counts[0], Math.min(counts[1], counts[2]));
        int max = Math.max(counts[0], Math.max(counts[1], counts[2]));
        System.out.println("3,000,000 x nextInt(3): counts within 0.2% of each other: "
                + ((max - min) < 6000));
    }
}

Output:

Output
seed 42, two generators: 341 and 341
Math.random() in [0, 1): true
ThreadLocalRandom roll in [1, 6]: true
RandomGenerator algorithms in this JDK: 13; default is L32X64MixRandom
L64X128MixRandom: state bits 192, splittable true, next in [0, 100): true
3,000,000 x nextInt(3): counts within 0.2% of each other: true
  • Two Random objects seeded with 42 produced the same dice rolls, 3, 4, 1. A fixed seed makes a test or simulation repeat exactly, which helps when you need to reproduce a failure.
  • The two-argument nextInt(1, 7) returns a value from 1 to 6. It arrived on Random in Java 17 through the RandomGenerator interface, and it avoids the off-by-one mistakes of nextInt(6) + 1 arithmetic.
  • The Math.random() method uses one shared Random object for the whole JVM. Threads calling it at the same time compete for its internal state, so concurrent code should use ThreadLocalRandom.current(), which gives each thread its own generator.
  • This JDK listed 13 algorithms through RandomGeneratorFactory.all(), and the default is L32X64MixRandom. The L64X128MixRandom generator has 192 bits of state and is splittable, so a parallel task can split it into independent streams.
  • The 3,000,000 calls to nextInt(3) filled the three counters to within 0.2% of each other. The bounded method is unbiased. Reducing a raw nextInt() with % is not, because the result can be negative and 232 does not divide evenly by 3.
  • None of these generators is safe for passwords, tokens or keys, because their output can be predicted from earlier values. Use java.security.SecureRandom for anything an attacker must not guess.

Math or StrictMath

The StrictMath class has the same methods as Math, but its specification requires results that are bit for bit identical to a reference C library called fdlibm on every platform. The Math class only promises results within one or two ulps (units in the last place) of the exact answer, and that freedom lets the JIT compiler replace calls with faster CPU instructions.

In practice the two usually agree, as the sin(PI/6) lines above did. Methods such as sqrt and abs are defined to be exact in both classes. Use StrictMath only when a result must be identical across machines, for example in a simulation replayed on another computer or in a test that compares exact double values. Since Java 17, plain floating-point arithmetic is always strict as well (JEP 306), so the strictfp keyword no longer changes anything.

Choosing the right method

Which Math method fits the task
TaskUseAvoid
Round a double to the nearest whole numberMath.round, or Math.rint for ties to even(int) x, which truncates toward zero
Round money to centsBigDecimal.setScale with a RoundingModeMath.round(x * 100) / 100.0
Index or bucket from a possibly negative numberMath.floorModMath.abs(h) % n, which can be negative
Detect integer overflowaddExact, multiplyExact, toIntExactPlain operators where wrapping would be a bug
Keep a value inside a rangeMath.clamp on Java 21 and laterNested max and min calls that are easy to swap
Check for a missing or invalid doubleDouble.isNaN, Double.isFinitex == Double.NaN, which is always false
Random numbers in one thread or in testsnew Random(seed) or RandomGenerator.ofnextInt() % n
Random numbers in many threadsThreadLocalRandom.current()A shared Random or Math.random()
Security tokens and keysSecureRandomEvery generator in java.util

Most mistakes with Math come from forgetting that double values are binary approximations and that int values wrap. The ranges and sizes of each primitive type are listed in Java data types.