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 +-*/%java.lang.MathMath.sqrt(2)
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.
| Group | Examples | Since | Best for |
|---|---|---|---|
| Basic functions | absmaxpowsqrtsinlog | 1.0 | Everyday formulas in double |
| Rounding | floorceilroundrint | 1.0 | Turning a double |
| Floor division and exact arithmetic | floorDivfloorModaddExacttoIntExact | 8 | Negative operands and overflow detection |
| Wide and fused operations | multiplyFullmultiplyHighfma | 9 | Products that need more than 64 bits or one rounding |
| Newer helpers | absExactceilDivclamp | 15 to 21 | Replacing hand-written versions of the same checks |
| Reproducible results | StrictMath | 1.3 | Bit-identical results on every platform |
| Random numbers | RandomThreadLocalRandomRandomGenerator | 1.0 to 17 | Simulations, 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.
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:
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
call returned 100. It is the Java 21 replacement for the commonMath.clamp(150, 0, 100) idiom, and it throws ifMath.max(min, Math.min(max, value)) is greater thanmin instead of returning nonsense.max - The
,pow ,sqrt and trigonometric methods take and returnlog . Evendouble printed 1024.0, so cast the result if you need anpow(2, 10) .int - The value
printed 0.49999999999999994, not 0.5. The constantsin(PI/6) is the closestMath.PI to pi, not pi itself, so the input was already slightly off beforedouble ran.sin - Trigonometric methods work in radians. The line with
gave the same 0.49999999999999994, because converting 30 degrees produces the same rounded value of pi divided by 6.toRadians(30) - The
result matchedStrictMath.sin here. The two classes are allowed to differ in the last bit, which the section on StrictMath below explains.Math.sin
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.
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:
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
method rounds toward negative infinity andfloor 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.ceil - The
method sends ties toward positive infinity, so 2.5 became 3 but -2.5 became -2, and -0.5 became 0. It returns around for along argument and andouble for aint .float - The
method rounds ties to the even neighbor (2.5 to 2.0, 3.5 to 4.0) and returns arint . This "banker's rounding" does not drift upward when you round many halfway values.double - 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
turned 1.005 into 1.0. TheMath.round(x * 100) / 100.0 line shows why: the stored double is 1.00499999999999989..., slightly below the tie. ABigDecimal built from the string "1.005" rounded correctly to 1.01, as covered inBigDecimalBigDecimal 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.
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:
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
with the message "/ by zero". TheArithmeticException divisions gave Infinity, -Infinity and NaN, anddouble andsqrt(-1) also returned special values instead of failing.log(0) - The comparison
printed false, because IEEE 754 defines NaN as unequal to everything. Test withNaN == NaN . The boxedDouble.isNaN returned true, so NaN keys still work in aDouble.equals , as described inHashMapequals and hashCode . - The call
returned NaN. Any NaN input poisons the result, so one bad value in a data set makes its maximum NaN rather than being skipped.Math.max(3, NaN) - Positive and negative zero compare equal with
, but== returned 1, ordering 0.0 above -0.0.Double.compare also treats -0.0 as smaller, and dividing 1 by -0.0 gave -Infinity, so the sign does change later results.Math.min - The call
returned NaN because 1.0/3 is not exactly one third, so the result would be a complex number. The dedicatedpow(-8, 1.0/3) method returned -2.0.cbrt - The value
is 2.0, which means doubles near 1016 are spaced two apart. Above about 9 x 1015 aMath.ulp(1e16) can no longer hold every whole number, which is why money and IDs belong indouble orlong .BigDecimal
Overflow and exact arithmetic
An int
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:
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
call threw "integer overflow" for the same input.addExact - The
method is the checked version of antoIntExact cast from(int) . It threw for 3,000,000,000, where a plain cast would have kept the low 32 bits, as shown inlongtype casting . - The
call returned 10,000,000,000 as amultiplyFull , wherelong in100000 * 100000 would overflow. Theint call returned 1, the top half of the 128-bit product ofmultiplyHigh and 4.Long.MAX_VALUE - The call
returned the same negative number, because +2,147,483,648 does not fit in anMath.abs(Integer.MIN_VALUE) . Theint method from Java 15 throws instead.absExact - This bites hash-based code. A
can behashCode() , and thenInteger.MIN_VALUE gave the invalid bucket -8. UsingMath.abs(h) % 10 gave 2, which is always in the range 0 to 9.Math.floorMod(h, 10) - The expression
printed 0.0, while0.1 * 10 - 1 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.Math.fma
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.
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:
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
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.Random - The two-argument
returns a value from 1 to 6. It arrived onnextInt(1, 7) in Java 17 through theRandom interface, and it avoids the off-by-one mistakes ofRandomGenerator arithmetic.nextInt(6) + 1 - The
method uses one sharedMath.random() object for the whole JVM. Threads calling it at the same time compete for its internal state, so concurrent code should useRandom , which gives each thread its own generator.ThreadLocalRandom.current() - This JDK listed 13 algorithms through
, 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.RandomGeneratorFactory.all() - The 3,000,000 calls to
filled the three counters to within 0.2% of each other. The bounded method is unbiased. Reducing a rawnextInt(3) withnextInt() 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
for anything an attacker must not guess.java.security.SecureRandom
Math or StrictMath
The StrictMathMathMath
In practice the two usually agree, as the sin(PI/6)sqrtabsStrictMathdoublestrictfp
Choosing the right method
| Task | Use | Avoid |
|---|---|---|
| Round a double to the nearest whole number | Math.roundMath.rint | (int) x |
| Round money to cents | BigDecimal.setScaleRoundingMode | Math.round(x * 100) / 100.0 |
| Index or bucket from a possibly negative number | Math.floorMod | Math.abs(h) % n |
| Detect integer overflow | addExactmultiplyExacttoIntExact | Plain operators where wrapping would be a bug |
| Keep a value inside a range | Math.clamp | Nested maxmin |
| Check for a missing or invalid double | Double.isNaNDouble.isFinite | x == Double.NaN |
| Random numbers in one thread or in tests | new Random(seed)RandomGenerator.of | nextInt() % n |
| Random numbers in many threads | ThreadLocalRandom.current() | A shared RandomMath.random() |
| Security tokens and keys | SecureRandom | Every generator in java.util |
Most mistakes with Mathdoubleint