Math Class
Java’s Math class is your built-in scientific calculator. It lives in java.lang (automatically imported), so you never need an import statement — just call Math.methodName() and you’re good to go.
What Is the Math Class?
java.lang.Math is a final utility class packed with static methods and two constants for common mathematical operations — rounding, exponentiation, trigonometry, logarithms, and more. Because every method is static, you never instantiate Math; you simply call methods directly on the class.
double result = Math.sqrt(25); // 5.0 — no 'new Math()' needed
Note: The
Mathclass constructor is private, so you literally cannot create aMathobject. It is intentionally designed as a stateless utility class.
Two Important Constants
Math provides two mathematical constants you will use often:
| Constant | Value (approx.) | Meaning |
|---|---|---|
Math.PI | 3.141592653589793 | Ratio of circumference to diameter |
Math.E | 2.718281828459045 | Base of natural logarithm |
double circumference = 2 * Math.PI * 5; // circle with radius 5
System.out.println(circumference);
Output:
31.41592653589793
Absolute Value — Math.abs()
Returns the positive (non-negative) version of a number. Works with int, long, float, and double.
System.out.println(Math.abs(-42)); // 42
System.out.println(Math.abs(-3.14)); // 3.14
System.out.println(Math.abs(7)); // 7
Output:
42
3.14
7
Power and Square Root
Math.pow(base, exponent)
Raises base to the power of exponent. Both parameters and the return value are double.
double squared = Math.pow(3, 2); // 9.0
double cubed = Math.pow(2, 10); // 1024.0
System.out.println(squared + ", " + cubed);
Output:
9.0, 1024.0
Math.sqrt(x)
Returns the positive square root of x.
System.out.println(Math.sqrt(144)); // 12.0
System.out.println(Math.sqrt(2)); // 1.4142135623730951
Math.cbrt(x)
Returns the cube root of x (introduced in Java 1.5).
System.out.println(Math.cbrt(27)); // 3.0
System.out.println(Math.cbrt(-8)); // -2.0
Rounding Methods
Java’s Math class offers four rounding methods — each with subtly different behavior:
| Method | What it does | Example (x = 2.7) |
|---|---|---|
Math.ceil(x) | Round up to nearest integer | 3.0 |
Math.floor(x) | Round down to nearest integer | 2.0 |
Math.round(x) | Round to nearest integer | 3 |
Math.rint(x) | Round to nearest, returns double | 3.0 |
double x = 2.7;
System.out.println(Math.ceil(x)); // 3.0
System.out.println(Math.floor(x)); // 2.0
System.out.println(Math.round(x)); // 3
System.out.println(Math.rint(x)); // 3.0
double y = 2.5;
System.out.println(Math.round(y)); // 3 (rounds toward positive infinity)
System.out.println(Math.rint(y)); // 2.0 (rounds to even — "banker's rounding")
Tip:
Math.round()andMath.rint()differ when the value is exactly 0.5.round()always goes toward positive infinity;rint()uses “round half to even” (banker’s rounding), which reduces statistical bias in large datasets.
Minimum and Maximum
System.out.println(Math.min(10, 20)); // 10
System.out.println(Math.max(10, 20)); // 20
System.out.println(Math.min(-5, -3)); // -5
System.out.println(Math.max(3.14, 2.71)); // 3.14
Both min and max are overloaded for int, long, float, and double.
Logarithms and Exponentials
System.out.println(Math.log(Math.E)); // 1.0 (natural log, base e)
System.out.println(Math.log10(1000)); // 3.0 (base-10 log)
System.out.println(Math.exp(1)); // 2.718281828459045 (e^1)
System.out.println(Math.exp(2)); // 7.38905609893065 (e^2)
Note:
Math.log()is the natural logarithm (base e), not base 10. UseMath.log10()for base-10 logarithms. For any other baseb, apply the change-of-base formula:Math.log(x) / Math.log(b).
Trigonometric Methods
All trig methods work in radians, not degrees. Use Math.toRadians() to convert.
double degrees = 90;
double radians = Math.toRadians(degrees);
System.out.println(Math.sin(radians)); // 1.0
System.out.println(Math.cos(radians)); // ~0.0 (floating-point near-zero)
System.out.println(Math.tan(radians)); // very large number (tan 90° is undefined)
The inverse functions — Math.asin(), Math.acos(), Math.atan() — return results in radians. Use Math.toDegrees() to convert back.
double angle = Math.toDegrees(Math.asin(1.0));
System.out.println(angle); // 90.0
Random Numbers — Math.random()
Math.random() returns a pseudo-random double in the range [0.0, 1.0) (inclusive of 0, exclusive of 1).
double rand = Math.random();
System.out.println(rand); // e.g. 0.7341829...
To get a random integer in a range [min, max]:
int min = 1, max = 6;
int dice = (int)(Math.random() * (max - min + 1)) + min;
System.out.println("Rolled: " + dice); // 1 to 6
Tip: For more control — thread safety, better distribution, or reproducibility — prefer
java.util.Random,ThreadLocalRandom, orSecureRandomoverMath.random(). See the collections and concurrency sections for context on when that matters.
Hyperbolic Functions
Java also provides Math.sinh(), Math.cosh(), and Math.tanh() for hyperbolic trigonometry — useful in physics and engineering simulations.
System.out.println(Math.sinh(1)); // 1.1752011936438014
System.out.println(Math.cosh(0)); // 1.0
System.out.println(Math.tanh(1)); // 0.7615941559557649
Math.signum() and Math.copySign()
signum() returns -1.0, 0.0, or 1.0 depending on the sign of the value — handy for comparators and direction logic.
System.out.println(Math.signum(-15.0)); // -1.0
System.out.println(Math.signum(0.0)); // 0.0
System.out.println(Math.signum(42.0)); // 1.0
copySign(magnitude, sign) returns magnitude with the sign of sign:
System.out.println(Math.copySign(5.0, -1.0)); // -5.0
System.out.println(Math.copySign(-3.0, 1.0)); // 3.0
Exact Arithmetic — Overflow-Safe Methods (Java 8+)
Standard arithmetic in Java silently wraps on overflow. The *Exact family throws ArithmeticException instead:
try {
int result = Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
System.out.println("Overflow detected: " + e.getMessage());
}
Output:
Overflow detected: integer overflow
Available exact methods: addExact, subtractExact, multiplyExact, incrementExact, decrementExact, negateExact, and toIntExact.
Tip: Use the
*Exactmethods in financial, safety-critical, or any domain where silent overflow would be disastrous. They are a much safer alternative to manual bounds checking.
Quick Reference — All Common Methods
| Method | Description |
|---|---|
Math.abs(x) | Absolute value |
Math.pow(a, b) | a raised to the power b |
Math.sqrt(x) | Square root |
Math.cbrt(x) | Cube root |
Math.ceil(x) | Round up |
Math.floor(x) | Round down |
Math.round(x) | Round to nearest |
Math.min(a, b) | Smaller of two values |
Math.max(a, b) | Larger of two values |
Math.log(x) | Natural logarithm (base e) |
Math.log10(x) | Base-10 logarithm |
Math.exp(x) | e raised to the power x |
Math.sin/cos/tan(x) | Trig functions (radians) |
Math.random() | Random double [0.0, 1.0) |
Math.signum(x) | Sign: -1, 0, or 1 |
Math.addExact(a, b) | Overflow-safe addition (Java 8+) |
Under the Hood
At the JVM level, Math methods are often recognized as intrinsics — the JIT compiler replaces them with a single native CPU instruction rather than executing Java bytecode. For example, Math.sqrt() typically compiles down to the x86 FSQRT instruction, and Math.abs() on integers maps to a branch-free bit manipulation sequence. This makes Math methods extremely fast — often faster than hand-written alternatives.
Math.random() internally delegates to a single, lazily initialized java.util.Random instance. Because it is shared across threads, it uses synchronization, which can be a bottleneck under heavy concurrent load. ThreadLocalRandom.current().nextDouble() avoids that contention by giving each thread its own generator.
The StrictMath class (also in java.lang) is a sibling to Math. While Math allows platform-specific floating-point optimizations that can produce slightly different results on different hardware, StrictMath guarantees bit-for-bit identical results everywhere by using a reference implementation (fdlibm). Choose StrictMath when reproducibility across platforms matters more than raw speed.
Related Topics
- Wrapper Classes — autoboxing primitives and parsing numbers from strings
- Variables — understanding
int,double, and other primitive types used with Math - Operators — built-in arithmetic operators that complement Math methods
- Recursion — using Math methods inside recursive algorithms like factorial and Fibonacci
- Stream API — combining
Mathwith streams for bulk numerical operations - Random & Collections Utility — higher-level utilities built on top of random and ordering logic