Nearby lessons
52 of 125Java - Math Class
📌 What You Will Learn
- Use the Math class for common maths operations
- Know the important Math methods
- Generate random numbers with Math.random()
Learn the Java Math class — ready-made static methods for maximum, minimum, power, square root, absolute value, rounding and random numbers.
What is the Math Class?
The Math class lives in java.lang (so no import is needed) and gives you static methods for common maths operations. Call them with the class name: Math.max(...).
In simple words: Math is a free calculator built into Java — you call
Math.something() and it does the maths for you.Important Methods
| Method | What it does | Example |
|---|---|---|
Math.max(a, b) | Larger of two values | Math.max(4, 9) → 9 |
Math.min(a, b) | Smaller of two values | Math.min(4, 9) → 4 |
Math.pow(a, b) | a raised to power b | Math.pow(2, 3) → 8.0 |
Math.sqrt(x) | Square root | Math.sqrt(25) → 5.0 |
Math.abs(x) | Absolute value | Math.abs(-7) → 7 |
Math.round(x) | Rounds to nearest long | Math.round(3.6) → 4 |
Math.random() | Random double in [0.0, 1.0) | Math.random() → 0.47... |
Math in Action
See the most-used methods working in one program:
Example03
Random Numbers
Math.random() returns a double between 0.0 (inclusive) and 1.0 (exclusive). Multiply and cast to get a whole number in a range:
Example04
📝 Key Takeaways
- Math is a final class in java.lang — no import needed
- Methods like max, min, pow, sqrt, abs are all static
- Math.random() gives a double between 0.0 and 1.0