The Math class in Java is a built-in utility class that provides common mathematical
functions. It is part of java.lang, so it does not require an import statement.
All methods in the Math class are static, meaning you call them using the class name:
Math.methodName(parameters);
You never create a Math object.
Math.sqrt()Returns the square root of a number.
double result = Math.sqrt(25); // result = 5.0
Math.pow()Raises a number to a specific power.
double result = Math.pow(3, 4); // result = 81.0
Math.random()Generates a value from 0.0 up to 1.0 (but not including 1.0).
double r = Math.random(); // r is between 0.0 and 1.0
General formula:
(int)(Math.random() * range + start)
// Random int 0–9
int num = (int)(Math.random() * 10);
// Random int 1–6 (dice)
int roll = (int)(Math.random() * 6 + 1);
// Random int 5–15
int n = (int)(Math.random() * 11 + 5);
Math.abs()int x = Math.abs(-12); // 12
Math.round(x) – nearest whole numberMath.floor(x) – rounds downMath.ceil(x) – rounds upMath.round(3.6); // 4
Math.floor(3.6); // 3.0
Math.ceil(3.1); // 4.0
The Math class is used frequently in:
| Method | Purpose | Returns | Example |
|---|---|---|---|
Math.sqrt(x) |
Square root | double | Math.sqrt(16) → 4.0 |
Math.pow(a, b) |
a to the power of b | double | Math.pow(2, 3) → 8.0 |
Math.random() |
Random number 0.0–1.0 | double | Math.random() |
Math.abs(x) |
Absolute value | int/double | Math.abs(-5) |
Math.round(x) |
Rounds to nearest | long/int | Math.round(2.7) |
Math.floor(x) |
Rounds down | double | Math.floor(2.7) |
Math.ceil(x) |
Rounds up | double | Math.ceil(2.1) |
Math.sqrt(89);Math.pow(7, 3);(int)(Math.random() * 100 + 1);Math.abs(x - y);