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.
Related Tutorials
Frequently Asked Questions (FAQ)
Q1. What is the Math class in Java?
A final class in java.lang containing static methods and constants for mathematical operations.
Q2. Can I create an object of Math?
No. Its constructor is private; call its static methods directly.
Q3. What is the difference between round, ceil and floor?
round goes to the nearest integer, ceil always up, and floor always down.
Q4. What does Math.round(-2.5) return?
-2, because halves are rounded towards positive infinity.
Q5. Why does Math.pow return a double?
It supports fractional and negative exponents. Cast the result, or use multiplication or BigInteger.pow for exact integers.
Q6. 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).
Q7. Is Math.random() secure?
No. Use SecureRandom for passwords, tokens and keys.
Q8. How do I round to two decimal places?
For display, String.format("%.2f", x). For calculations, Math.round(x * 100) / 100.0 or, for money, BigDecimal.setScale(2, RoundingMode.HALF_UP).
Q9. What does Math.sqrt of a negative number return?
NaN (not a number).
Q10. 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.
Q11. What are the addExact methods for?
They perform integer arithmetic that throws ArithmeticException on overflow instead of silently wrapping around.
Q12. What is the difference between % and Math.floorMod?
% takes the sign of the dividend (-7 % 2 == -1); floorMod takes the sign of the divisor (floorMod(-7, 2) == 1).
Q13. Do trigonometric methods use degrees?
No, radians. Convert with Math.toRadians and Math.toDegrees.
Q14. What constants does Math provide?
Math.PI, Math.E and, since Java 19, Math.TAU (2π).
Q15. What is the difference between Math and StrictMath?
StrictMath guarantees identical results on all platforms; Math may use faster platform-specific implementations.
Q16. What does Math.clamp do?
Added in Java 21, it limits a value to a range: clamp(15, 0, 10) returns 10.
Q17. Why is 0.1 + 0.2 not 0.3?
Doubles store binary approximations, and 0.1 and 0.2 cannot be represented exactly. Use BigDecimal for exact decimal arithmetic.
Q18. Can I avoid writing Math. every time?
Yes, with import static java.lang.Math.*;, used sparingly for readability.
Q19. What does Math.hypot do?
It computes √(x² + y²) accurately, avoiding overflow or underflow in the intermediate squares.
Q20. Which class handles very large integers?
java.math.BigInteger, which supports arbitrary-precision integer arithmetic.