The Math Class
Reviewed & published by Brayan K
The operators + - * / only go so far. When you need square roots, powers, rounding, absolute values, or random numbers, Java's built-in Math class has a ready-made method waiting — no import required.
Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- That Math is static — no import, no object
- abs, max, min, pow, sqrt and friends
- round vs ceil vs floor
- The constants Math.PI and Math.E
- Generating random numbers in a range
- Real formulas: distance, interest, clamping
1️⃣ Math Is a Toolbox, Not an Object
The Math class is a collection of static methods. "Static" means they belong to the class itself, so you call them directly on the class name and never create an instance:
Math math = new Math(); // ❌ you NEVER do this
double root = Math.sqrt(25); // ✅ call it on the class -> 5.0💡 Analogy: Math is like a wall-mounted toolbox in a workshop. You don't buy your own copy of the toolbox — you just walk up and grab the tool you need (Math.sqrt, Math.max) and put it back.
2️⃣ The Methods You'll Actually Use
| Method | Does | Example → result |
|---|---|---|
| Math.abs(x) | Absolute value | abs(-7) → 7 |
| Math.max(a,b) | Larger of two | max(3,9) → 9 |
| Math.min(a,b) | Smaller of two | min(3,9) → 3 |
| Math.pow(a,b) | a to the power b | pow(2,10) → 1024.0 |
| Math.sqrt(x) | Square root | sqrt(144) → 12.0 |
| Math.round(x) | Nearest whole (long) | round(4.5) → 5 |
| Math.ceil(x) | Round up (double) | ceil(4.1) → 5.0 |
| Math.floor(x) | Round down (double) | floor(4.9) → 4.0 |
| Math.random() | Random 0.0–1.0 | → 0.6273... |
public class Main {
public static void main(String[] args) {
// The Math class is in java.lang, so NO import is needed.
// Every method is static: you call Math.something(...).
System.out.println("Math.abs(-7) = " + Math.abs(-7));
System.out.println("Math.max(3, 9) = " + Math.max(3, 9));
System.out.println("Math.min(3, 9) = " + Math.min(3, 9));
System.out.println("Math.pow(2, 10) = " + Math.pow(2, 10)); // 2^10
System.out.println("Math.sqrt(144) = " + Math.sqrt(144));
System.out.println("Math.cbrt(27) = " + Math.cbrt(27));
// Rounding family
System.out.println("Math.round(4.5) = " + Math.round(4.5)); // 5
System.out.println("Math.ceil(4.1) = " + Math.ceil(4.1)); // 5.0
System.out.println("Math.floor(4.9) = " + Math.floor(4.9)); // 4.0
// Useful constants
System.out.println("Math.PI = " + Math.PI);
System.out.println("Math.E = " + Math.E);
}
}3️⃣ Random Numbers
Math.random() returns a double in the half-open range [0.0, 1.0) — zero is possible, one is not. To turn that into a useful integer range, memorise this formula:
int n = (int)(Math.random() * (max - min + 1)) + min;
// inclusive of BOTH min and maxFor a six-sided die that's min = 1, max = 6. The (max - min + 1) gives the count of possible values, and the + min shifts the range to start at the right place.
Since the output is random, the numbers in the example below will differ every time you run it — that's the whole point!
public class Main {
public static void main(String[] args) {
// Math.random() returns a double in the range [0.0, 1.0)
double r = Math.random();
System.out.println("Raw random: " + r); // e.g. 0.6273...
// FORMULA: random int from min..max (inclusive)
// (int)(Math.random() * (max - min + 1)) + min
int min = 1, max = 6;
int dieRoll = (int)(Math.random() * (max - min + 1)) + min;
System.out.println("Dice roll (1-6): " + dieRoll);
// Simulate three coin flips
for (int i = 1; i <= 3; i++) {
String side = Math.random() < 0.5 ? "Heads" : "Tails";
System.out.println("Flip " + i + ": " + side);
}
}
}4️⃣ Putting Math to Work
The real value of Math shows up when you combine methods into a formula. A few classics:
- Distance between two points: Math.sqrt(dx² + dy²) (or the safer Math.hypot).
- Compound interest: principal * Math.pow(1 + rate, years).
- Clamping a value into a range: Math.max(lo, Math.min(hi, value)).
public class Main {
public static void main(String[] args) {
// Distance between two points using the Pythagorean theorem.
double x1 = 0, y1 = 0;
double x2 = 3, y2 = 4;
double dx = x2 - x1;
double dy = y2 - y1;
double distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
System.out.printf("Distance = %.1f%n", distance); // 5.0
// Hypotenuse helper does the same thing more safely
System.out.printf("Math.hypot = %.1f%n", Math.hypot(dx, dy));
// Compound interest: P * (1 + r)^years
double principal = 1000;
double rate = 0.05;
int years = 10;
double future = principal * Math.pow(1 + rate, years);
System.out.printf("$1000 at 5%% for 10 years = $%.2f%n", future);
// Clamp a value into a range using max + min
int score = 137;
int clamped = Math.max(0, Math.min(100, score));
System.out.println("Clamped score: " + clamped); // 100
}
}public class Main {
public static void main(String[] args) {
// 🎯 YOUR TURN — replace each ___ using the hint beside it.
double price = 12.3456;
// 1) Nearest whole number. Comes back as a long, not a double.
System.out.println("Rounded: " + Math.___(price)); // 👉 replace ___ with round
// 2) Always up, even from .0001.
System.out.println("Up: " + Math.___(price)); // 👉 replace ___ with ceil
// 3) Always down, even from .9999.
System.out.println("Down: " + Math.___(price)); // 👉 replace ___ with floor
System.out.println("Abs: " + Math.abs(-7.5));
// 4) The larger of the two.
System.out.println("Bigger: " + Math.___(12, 30)); // 👉 replace ___ with max
System.out.println("Smaller: " + Math.min(12, 30));
System.out.println("Power: " + Math.pow(2, 10));
// 5) The square root — 144 gives 12.0, a double.
System.out.println("Root: " + Math.___(144)); // 👉 replace ___ with sqrt
// The two-decimal trick: scale up, round, divide by a DOUBLE 100.0.
double toTwoPlaces = Math.round(price * 100) / 100.0;
System.out.println("Two places: " + toTwoPlaces);
}
}🧩 Reorder Challenge
Reorder these lines to compute the hypotenuse of a 3-4-5 triangle and print it as a rounded int.
long rounded = Math.round(h);
double h = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse: " + rounded);
double a = 3, b = 4;double a = 3, b = 4;
double h = Math.sqrt(a * a + b * b);
long rounded = Math.round(h);
System.out.println("Hypotenuse: " + rounded);Why: a and b must exist before the sqrt uses them. h (which is 5.0) must be computed before it can be rounded, and the rounded value is printed last. The output is Hypotenuse: 5.
🧠 Quick Recall
1. What does this print?
System.out.println(Math.ceil(7.01));8.0. ceil always rounds up, and it returns a double, so note the .0.
2. What does this print?
System.out.println(Math.max(0, Math.min(100, 250)));100. The inner min(100, 250) is 100, then max(0, 100) is 100 — the clamp formula in action.
3. What is the type and possible range of (int)(Math.random() * 10)?
An int from 0 to 9 inclusive. Math.random() never reaches 1.0, so * 10 never reaches 10, and the cast truncates to 0–9.
Common Beginner Mistakes
- ❌ Trying to instantiate it: new Math() doesn't work — every method is static.
- ❌ Forgetting pow returns a double: int x = Math.pow(2, 3); fails. Cast it: (int) Math.pow(2, 3).
- ❌ Off-by-one in random ranges: forgetting the + 1 means you can never roll the max value.
- ❌ Confusing round/ceil/floor: ceil and floor return doubles; round returns a long.
- ❌ Integer division inside Math: Math.sqrt(9/2) is Math.sqrt(4) = 2.0; write 9.0/2 for 4.5.
📋 Quick Reference
| Method | Returns | Example → result |
|---|---|---|
| Math.abs(x) | Absolute value | Math.abs(-7) → 7 |
| Math.max(a, b) | Larger of two | Math.max(3, 9) → 9 |
| Math.min(a, b) | Smaller of two | Math.min(3, 9) → 3 |
| Math.pow(a, b) | a to the power b (double) | Math.pow(2, 10) → 1024.0 |
| Math.sqrt(x) | Square root (double) | Math.sqrt(144) → 12.0 |
| Math.cbrt(x) | Cube root (double) | Math.cbrt(27) → 3.0 |
| Math.round(x) | Nearest whole (long) | Math.round(4.5) → 5 |
| Math.ceil(x) | Round up (double) | Math.ceil(4.1) → 5.0 |
| Math.floor(x) | Round down (double) | Math.floor(4.9) → 4.0 |
| Math.hypot(a, b) | √(a²+b²), safely | Math.hypot(3, 4) → 5.0 |
| Math.random() | Random double in [0.0, 1.0) | → 0.6273... |
| (int)(Math.random()*(max-min+1))+min | Random int, min..max inclusive | die: min 1, max 6 |
| Math.PI | Constant π | 3.141592653589793 |
| Math.E | Constant e | 2.718281828459045 |
🎉 Lesson Complete!
You've unlocked Java's math toolbox: abs, max/min, pow, sqrt, the rounding trio, the constants PI and E, and the random-number formula. No imports, no objects — just Math.something(...).
Practice quiz
What does Math.ceil(7.01) print?
- 7.0
- 7
- 8.0
- 8
Answer: 8.0. ceil always rounds UP to the next whole number and returns a double, so 7.01 becomes 8.0.
What does Math.max(0, Math.min(100, 250)) evaluate to?
- 100
- 0
- 250
- 150
Answer: 100. The inner min(100, 250) is 100, then max(0, 100) is 100 — the standard clamp formula.
What is the type and result of Math.pow(2, 10)?
- int 1024
- long 1024
- float 1024.0f
- double 1024.0
Answer: double 1024.0. Math.pow takes two doubles and returns a double, so the result is 1024.0, not the int 1024.
Do you need to import the Math class to use Math.sqrt?
- Yes, import java.lang.Math
- No — it lives in java.lang
- Yes, import java.util.Math
- No — but you must call new Math()
Answer: No — it lives in java.lang. Math is in java.lang, which is imported automatically. There is nothing to import and nothing to instantiate.
What does Math.round(4.5) return?
- 5
- 4
- 4.0
- 5.0
Answer: 5. round returns the nearest whole number as a long; 4.5 rounds to 5.
Which call gives a random int from 1 to 6 inclusive?
- (int)(Math.random() * 6)
- (int)(Math.random() * 7)
- (int)(Math.random() * 6) + 1
- Math.random() * 6 + 1
Answer: (int)(Math.random() * 6) + 1. Math.random() is in [0.0, 1.0), so * 6 gives 0–5; adding 1 shifts it to the inclusive 1–6 range.
What does Math.floor(4.9) print?
- 5.0
- 4.0
- 4
- 5
Answer: 4.0. floor always rounds DOWN and returns a double, so 4.9 becomes 4.0.
Why does new Math() fail to compile?
- Math is final
- Math is an interface
- Math is abstract
- Math has no public constructor and only static methods
Answer: Math has no public constructor and only static methods. Every method on Math is static and it has no public constructor, so you never instantiate it — you call Math.something(...).
What does Math.sqrt(9 / 2) print?
- 2.1213...
- 2.0
- 4.5
- Compile error
Answer: 2.0. 9 / 2 is integer division giving 4, so Math.sqrt(4) is 2.0. Write 9.0 / 2 to get 4.5 first.
What is the value of Math.cbrt(27)?
- 9.0
- 3
- 3.0
- 27.0
Answer: 3.0. cbrt is the cube root and returns a double, so the cube root of 27 is 3.0.
Continue this course
- Previous: User Input with Scanner
- Next: StringBuilder & Formatting — Build strings efficiently and format with printf / String.format
- Quick reference: Java cheat sheet
Frequently asked questions
Do I need to import the Math class?
No. Math lives in java.lang, which is imported into every program automatically — just like String and System. You call its methods directly as Math.sqrt(...), Math.pow(...), and so on. There is nothing to import and nothing to instantiate.
Why do I write Math.sqrt() instead of creating a Math object?
Every method on Math is static, meaning it belongs to the class itself rather than to an instance. You never write new Math(). Static methods are perfect for pure functions like square root that just take inputs and return a result with no stored state.
What is the difference between Math.round, Math.ceil, and Math.floor?
Math.round returns the nearest whole number (4.5 rounds to 5) as a long. Math.ceil always rounds UP to the next whole number (4.1 becomes 5.0) and returns a double. Math.floor always rounds DOWN (4.9 becomes 4.0) and returns a double. Casting with (int) is different again — it just truncates the fraction.
How do I get a random integer in a specific range?
Math.random() returns a double from 0.0 up to (but not including) 1.0. The standard formula for an inclusive range is (int)(Math.random() * (max - min + 1)) + min. For a die you'd use min 1 and max 6. For more control or thread-safe generation, java.util.Random or ThreadLocalRandom are better tools.
Why does Math.pow return a double even for whole-number inputs?
Math.pow is declared to take two doubles and return a double, so Math.pow(2, 10) gives 1024.0, not 1024. If you need an int, cast the result: (int) Math.pow(2, 10). Be aware that for very large exponents the double result can lose precision, so for exact integer powers a manual loop or BigInteger may be safer.