Using the Math Class
Math's Static Methods
Math is a built-in class of static methods — no object, no new, just call it directly by its class name:
Math.abs(-4); // 4 — absolute value
Math.pow(2, 3); // 8.0 — 2 to the power of 3
Math.sqrt(9); // 3.0
Math.random(); // a double >= 0.0 and < 1.0
These all return a value, so — same rule as the last lesson — you must actually use what they return.
Random Numbers in a Range
Math.random() alone gives a double in [0.0, 1.0) — including 0.0, never reaching 1.0. That's rarely useful on its own; you stretch and shift it to get the range you actually want:
int rnd = (int)(Math.random() * 10); // an int from 0-9 (10 possible values)
int rnd2 = (int)(Math.random() * 10) + 1; // an int from 1-10 (shifted up by 1)
The general recipe: multiply by how many values you want, cast to int to drop the decimal, then add the minimum to shift the whole range up.
// A random autonomous delay between 1 and 4 seconds
double delay = Math.random() * 3.0 + 1.0; // [1.0, 4.0)
// A random starting position index, 0 through 2 (3 choices)
int startPos = (int)(Math.random() * 3);
The parentheses matter: (int)(Math.random() * 10) casts the whole scaled expression; (int)Math.random() * 10 casts Math.random() alone first — which truncates it to 0 every time, then multiplies by 10, always giving 0.
Common Pitfalls
- Forgetting the parentheses around the scaled expression.
(int)Math.random() * 10always evaluates to0— the cast has to wrap the wholeMath.random() * rangeexpression. - Off-by-one on the range size. For an inclusive range like 1-10, the range size is
10, not9— count how many distinct values you actually want. - Ignoring the return value.
Math.abs(x);on its own line compiles but does nothing useful — the result has to be stored or used.
Key Takeaways
Mathmethods are static — call them asMath.methodName(...), no object needed.Math.random()returns adoublein[0.0, 1.0)— 0.0 possible, 1.0 never reached.- To get a random int in a range:
(int)(Math.random() * range) + min, whererangeis the count of possible values. - The parentheses around
Math.random() * rangeare required — casting onlyMath.random()breaks the formula.
Derived from csawesome-2026: unit-1-using-objects-and-methods/1.11-using-the-math-class.md (CSA 1.11)