Math Class in Java – Methods and Examples
The java.lang.Math class provides static methods for common mathematical operations: absolute values, powers and roots, rounding, logarithms, trigonometry, random numbers and overflow-safe arithmetic, plus the constants PI and E. It is a final utility class with a private constructor, so you never create a Math object; you call Math.sqrt(x) directly.
This tutorial groups the most useful methods with runnable examples and points out the floating-point and overflow pitfalls every Java developer should know.
1. Basic Methods
public class BasicMath {
public static void main(String[] args) {
System.out.println("abs(-7.5) = " + Math.abs(-7.5));
System.out.println("max(4, 9) = " + Math.max(4, 9));
System.out.println("min(4, 9) = " + Math.min(4, 9));
System.out.println("pow(2, 10) = " + Math.pow(2, 10));
System.out.println("sqrt(144) = " + Math.sqrt(144));
System.out.println("cbrt(27) = " + Math.cbrt(27));
System.out.println("hypot(3, 4) = " + Math.hypot(3, 4));
System.out.println("exp(1) = " + Math.exp(1));
System.out.println("log(Math.E) = " + Math.log(Math.E));
System.out.println("log10(1000) = " + Math.log10(1000));
System.out.println("PI = " + Math.PI);
System.out.println("clamp(15,0,10) = " + Math.clamp(15, 0, 10)); // Java 21
}
}
abs(-7.5) = 7.5 max(4, 9) = 9 min(4, 9) = 4 pow(2, 10) = 1024.0 sqrt(144) = 12.0 cbrt(27) = 3.0 hypot(3, 4) = 5.0 exp(1) = 2.7182818284590455 log(Math.E) = 1.0 log10(1000) = 3.0 PI = 3.141592653589793 clamp(15,0,10) = 10
| Method | Returns |
|---|---|
abs(x) | Absolute value (int, long, float, double overloads) |
max(a, b), min(a, b) | Larger / smaller value |
pow(a, b) | ab as a double |
sqrt(x), cbrt(x) | Square root, cube root |
hypot(x, y) | √(x² + y²) without intermediate overflow |
exp(x), log(x), log10(x) | ex, natural log, base-10 log |
signum(x) | −1.0, 0.0 or 1.0 |
clamp(v, min, max) (Java 21) | v limited to the range |
2. Rounding Methods
public class Rounding {
public static void main(String[] args) {
double[] values = {2.4, 2.5, -2.5, -2.6};
System.out.println("value round ceil floor rint");
for (double v : values) {
System.out.printf("%5.1f %5d %5.1f %5.1f %5.1f%n",
v, Math.round(v), Math.ceil(v), Math.floor(v), Math.rint(v));
}
// Rounding to 2 decimal places for display
double price = 1234.5678;
System.out.println("2 decimals: " + Math.round(price * 100) / 100.0 + " | " + String.format("%.2f", price));
System.out.println("floorDiv(-7, 2) = " + Math.floorDiv(-7, 2) + ", -7 / 2 = " + (-7 / 2));
System.out.println("floorMod(-7, 2) = " + Math.floorMod(-7, 2) + ", -7 % 2 = " + (-7 % 2));
}
}
value round ceil floor rint 2.4 2 3.0 2.0 2.0 2.5 3 3.0 2.0 2.0 -2.5 -2 -2.0 -3.0 -2.0 -2.6 -3 -2.0 -3.0 -3.0 2 decimals: 1234.57 | 1234.57 floorDiv(-7, 2) = -4, -7 / 2 = -3 floorMod(-7, 2) = 1, -7 % 2 = -1
round: nearest integer, halves rounded up (towards positive infinity), returnslong(orintfor float).ceil: smallest integer ≥ x;floor: largest integer ≤ x; both returndouble.rint: nearest integer, halves to the even neighbour (banker's rounding).floorDiv/floorModround towards negative infinity, unlike/and%;floorModis handy for wrapping indexes.
For money, use BigDecimal with an explicit RoundingMode instead of rounding doubles.
3. Trigonometry and Random Numbers
import java.util.Random;
public class TrigAndRandom {
public static void main(String[] args) {
double angle = 30;
double rad = Math.toRadians(angle); // trig functions use radians
System.out.printf("sin(30°) = %.2f, cos(60°) = %.2f, tan(45°) = %.2f%n",
Math.sin(rad), Math.cos(Math.toRadians(60)), Math.tan(Math.toRadians(45)));
System.out.printf("atan2(1, 1) = %.0f degrees%n", Math.toDegrees(Math.atan2(1, 1)));
double r = Math.random(); // 0.0 <= r < 1.0
int dice = (int) (Math.random() * 6) + 1; // 1..6
System.out.println("random in [0,1): " + (r >= 0 && r < 1) + ", dice in 1..6: " + (dice >= 1 && dice <= 6));
Random seeded = new Random(42); // reproducible sequence
System.out.println("seeded nextInt(100): " + seeded.nextInt(100) + ", " + seeded.nextInt(100));
}
}
sin(30°) = 0.50, cos(60°) = 0.50, tan(45°) = 1.00 atan2(1, 1) = 45 degrees random in [0,1): true, dice in 1..6: true seeded nextInt(100): 30, 63
- Trigonometric functions use radians; convert with
toRadiansandtoDegrees. Math.random()returns a double in [0.0, 1.0). For integers, ranges and reproducibility, useRandom,ThreadLocalRandom.current().nextInt(1, 7), orSecureRandomfor security-sensitive values.
4. Overflow and Exact Arithmetic
Integer arithmetic silently wraps around on overflow. The *Exact methods throw ArithmeticException instead:
import java.math.BigDecimal;
public class ExactArithmetic {
public static void main(String[] args) {
int big = Integer.MAX_VALUE;
System.out.println("MAX_VALUE + 1 (silent overflow): " + (big + 1));
try {
Math.addExact(big, 1); // throws instead of overflowing
} catch (ArithmeticException e) {
System.out.println("addExact: ArithmeticException - " + e.getMessage());
}
System.out.println("multiplyExact(46341, 2) = " + Math.multiplyExact(46341, 2));
System.out.println("toIntExact(10L) = " + Math.toIntExact(10L));
System.out.println("0.1 + 0.2 (double) = " + (0.1 + 0.2));
System.out.println("0.1 + 0.2 (BigDecimal) = " + new BigDecimal("0.1").add(new BigDecimal("0.2")));
System.out.println("sqrt(-1) = " + Math.sqrt(-1) + ", 1.0 / 0 = " + (1.0 / 0));
}
}
MAX_VALUE + 1 (silent overflow): -2147483648 addExact: ArithmeticException - integer overflow multiplyExact(46341, 2) = 92682 toIntExact(10L) = 10 0.1 + 0.2 (double) = 0.30000000000000004 0.1 + 0.2 (BigDecimal) = 0.3 sqrt(-1) = NaN, 1.0 / 0 = Infinity
addExact,subtractExact,multiplyExact,negateExact,toIntExactdetect overflow.- Floating-point values are binary approximations:
0.1 + 0.2is not exactly0.3. UseBigDecimalfor exact decimals. - Invalid floating-point operations produce
NaNorInfinityrather than exceptions; check withDouble.isNaNandDouble.isInfinite.
5. Math vs StrictMath
StrictMath has the same methods but guarantees bit-for-bit identical results on every platform. Math may use faster CPU-specific implementations whose results can differ in the last bit. See strictfp keyword.
6. Summary
Mathis a final class of static methods; no object is needed.- Key groups: basic (abs, max, pow, sqrt), rounding (round, ceil, floor, rint), logs and trigonometry, random and exact arithmetic.
roundreturns a long;ceilandfloorreturn doubles.- Use the
*Exactmethods to catch overflow andBigDecimalfor exact decimal arithmetic.
7. Official Java Documentation References
Frequently Asked Questions (FAQ)
Q1. What is the difference between round, ceil and floor?
round goes to the nearest integer, ceil always up, and floor always down.
Q2. What does Math.round(-2.5) return?
-2, because halves are rounded towards positive infinity.
Q3. How do I generate a random number in a range?
(int) (Math.random() * (max - min + 1)) + min, or more clearly ThreadLocalRandom.current().nextInt(min, max + 1).
Q4. What is Math.abs(Integer.MIN_VALUE)?
Still Integer.MIN_VALUE (negative), because its absolute value does not fit in an int. Math.absExact (Java 15) throws instead.
Q5. What are the addExact methods for?
They perform integer arithmetic that throws ArithmeticException on overflow instead of silently wrapping around.
Q6. What does Math.clamp do?
Added in Java 21, it limits a value to a range: clamp(15, 0, 10) returns 10.