The Math Class
The Math toolbox
- The
Mathclass is a library of ready-made math class methods and constants. - No import and no object needed — just call
Math.something(...). - It covers powers, roots, rounding, absolute value, min/max, and more.
- It's the go-to for any calculation beyond the basic operators.
Common methods for AP
Math.abs(x)— absolute value:Math.abs(-5)is5.Math.pow(b, e)—bto the powere:Math.pow(2, 3)is8.0.Math.sqrt(x)— square root:Math.sqrt(9)is3.0.Math.max(a, b)/Math.min(a, b)— the larger / smaller of two values.
Random numbers
Math.random()returns adoublein the range0.0up to (but not including)1.0.- Scale and shift it for a range:
(int)(Math.random() * 6)gives0–5. - Add
1for a die roll:(int)(Math.random() * 6) + 1gives1–6. - The pattern
(int)(Math.random() * n) + startis worth memorizing.
Watch the return types
Math.powandMath.sqrtalways return adouble(e.g.8.0, not8).- To use the result as an
int, you must cast:(int) Math.pow(2, 3). Math.random()is adoubletoo — cast after scaling, not before.- Mixing up
intanddoublereturns is a classic Math-class slip.
Math.pow and Math.sqrt return a double, not an int. Math.pow(2, 3) is 8.0; store it in a double, or cast to use it as an int. And Math.random() gives a double in [0.0, 1.0) — the upper bound 1.0 is never returned. Build a whole-number range with (int)(Math.random() * n) + start.
A random die roll (1–6):
Math.random()→ a double like0.42.Math.random() * 6→0.0up to just under6.0(like2.52).(int)(Math.random() * 6) + 1→ truncates to2, then+1→3.
The Math class provides static methods: abs, pow, sqrt, max, min, and random. pow/sqrt return a double (cast for an int). Math.random() returns a double in [0.0, 1.0); build an integer range with (int)(Math.random() * n) + start.
Building a die roll from Math.random()
Scale, truncate, then shift to get 1-6.
What does Math.pow(2, 3) equal (as a number)?
2 to the power 3 = 8 (returned as the double 8.0).
Math.sqrt(9) returns a value of which type?
sqrt always returns a double — cast to use it as an int.
Math.random() returns a double in which range?
[0.0, 1.0) — the upper bound 1.0 is never returned.
Which expression gives a random integer from 1 to 6?
Scale by 6 → 0..5, truncate, then +1 → 1..6.
What is Math.abs(-5)?
Absolute value of −5 is 5.