Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- The
Mathclass is part of thejava.langpackage, so it is available by default. It contains only class methods. - The methods in the Java Quick Reference:
static int abs(int x),static double abs(double x),static double pow(double base, double exponent),static double sqrt(double x)andstatic double random(). Math.random()returns adoublethat is greater than or equal to 0.0 and less than 1.0.- Arithmetic and casting operators turn
Math.random()into a randomintordoublein a defined range. Each end of a range can be inclusive (the value can occur) or exclusive (it cannot).
Key relationships
| Call | Value | Type |
|---|---|---|
Math.abs(-7) |
7 |
int |
Math.abs(-2.5) |
2.5 |
double |
Math.pow(2, 5) |
32.0 |
double |
Math.pow(5, 0) |
1.0 |
double |
Math.sqrt(144) |
12.0 |
double |
(int) Math.pow(2, 10) |
1024 |
int |
| Want | Expression |
|---|---|
double in [0.0, 1.0) |
Math.random() |
int 0 to n - 1 |
(int) (Math.random() * n) |
int low to high, both inclusive |
(int) (Math.random() * (high - low + 1)) + low |
double low up to, not including, high |
Math.random() * (high - low) + low |
| int 1 to 6 | (int) (Math.random() * 6) + 1 |
Four questions for any random-number problem
- How many different values are wanted? That is the multiplier.
- What is the smallest value wanted? That is the shift added at the end.
- Is the result an
int(cast the whole product, then add the shift) or adouble(no cast)? - Test the extremes:
Math.random()equal to 0.0, and just under 1.0.
Assumptions and conventions
- Arguments of type
intare converted automatically todoubleparameters. - The Java Quick Reference is provided on the exam; you need to read and use it correctly.
- For a random expression you cannot say the output, only the possible range, so test the smallest (0.0) and largest (just under 1.0) values.
- Use
Math.sqrton non-negative values only; results for negative values are outside the course.
Mistakes to avoid
- Writing
(int) Math.random() * n. The cast truncatesMath.random()to 0 first, so the result is always 0. - Multiplying by
highinstead of by the number of values (high - low + 1). - Expecting 1.0 from
Math.random(). - Forgetting that
pow,sqrtandrandomreturndouble. Storing the result in anintneeds a cast. - Importing
Mathor creating aMathobject. - Thinking
absalways returnsdouble. - Adding the shift in the wrong place without checking the range.
Quick self-check
- What does
Math.sqrt(49)return, and what type? (7.0, adouble) - How many values are in the range 5 to 12 inclusive? (8)
- Write an expression for a random
intfrom 1 to 100 inclusive. ((int) (Math.random() * 100) + 1) - What is the range of
(int) (Math.random() * 10 + 5)? (5 to 14 inclusive) - What does
(int) Math.random() * 6 + 1always equal? (1)
Next: practice questions.