Unit 1 · 15 min
1.11 Math Class
The Math class gives you ready-made, tested class methods for common calculations.
Summary, objectives and course and exam description (CED) codes
The Math class is in the java.lang package, available by default, and contains only class methods. The Java Quick Reference lists five: abs(int), abs(double), pow, sqrt and random. Math.random() returns a double from 0.0 (inclusive) up to 1.0 (exclusive), and arithmetic and casting turn it into a random value in any range.
By the end of this session you can
- 1.11.A Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.
Reviewed against the CED on
1LearnThe notes, the traps and how to remember them
1. The Math class
The Math class is part of the java.lang package. Classes in the java.lang package are available by default, so you need no import 1.11.A.1. The Math class contains only class methods 1.11.A.2, so you call each one with the class name: Math.sqrt(2.25).
2. The five Math methods on the Java Quick Reference
These methods, what they do and when to use them are part of the Java Quick Reference 1.11.A.2:
| Method | Returns | Example |
|---|---|---|
static int abs(int x) |
the absolute value of an int |
Math.abs(-4) is 4 |
static double abs(double x) |
the absolute value of a double |
Math.abs(-4.5) is 4.5 |
static double pow(double base, double exponent) |
base raised to the power exponent |
Math.pow(2, 10) is 1024.0 |
static double sqrt(double x) |
the non-negative square root of x |
Math.sqrt(2.25) is 1.5 |
static double random() |
a double from 0.0 (included) up to 1.0 (not included) |
at least 0.0 and less than 1.0 |
System.out.println(Math.abs(-4));
System.out.println(Math.abs(-4.5));
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(2.25));
double side = Math.sqrt(49);
System.out.println("Side: " + side);
Output:
4
4.5
1024.0
1.5
Side: 7.0
Math.pow(2, 10) has int arguments, but the parameters are double, so the arguments are widened and the result is a double.
Watch out: pow and sqrt return a double, even with int arguments, so Math.pow(2, 3) prints 8.0, not 8, and int p = Math.pow(2, 3); does not compile without a cast:
// does not compile
int p = Math.pow(2, 3);
Real view:
error: incompatible types: possible lossy conversion from double to int
int p = (int) Math.pow(2, 3); compiles and stores 8.
3. Random numbers in a range
The values returned from Math.random() can be changed with arithmetic and casting operators to produce a random int or double in a defined range. Each endpoint of the range can be inclusive, meaning the value can occur, or exclusive, meaning it cannot 1.11.A.3.
Building a die roll, int die = (int) (Math.random() * 6) + 1;, step by step:
| Step | Expression | Possible values | What it does |
|---|---|---|---|
| 1 | Math.random() |
0.0 up to 1.0 | 1.0 is never returned |
| 2 | ... * 6 |
0.0 up to 6.0 | stretches to 6 values |
| 3 | (int) (...) |
0, 1, 2, 3, 4, 5 | drops the decimal part |
| 4 | ... + 1 |
1, 2, 3, 4, 5, 6 | shifts: the lowest is 1 |
Pattern: (int) (Math.random() * (max - min + 1)) + min gives an int from min to max, both inclusive 1.11.A.3.
You cannot predict a random value, but you can test the two extremes. Here r stands in for the smallest and a very large value that Math.random() could return:
double r = 0.0; // smallest possible value
System.out.println((int) (r * 6) + 1);
r = 0.9999999; // just below 1.0
System.out.println((int) (r * 6) + 1);
System.out.println((int) r * 6 + 1); // cast too early
Output:
1
6
1
The last line shows the trap: (int) r is 0 for every value below 1.0, so the result is always 1.
A random double in a range works the same way, without the cast. Math.random() * 5 + 10 gives a double from 10.0 (inclusive) up to 15.0 (exclusive):
double r = 0.0;
System.out.println(r * 5 + 10);
r = 0.5;
System.out.println(r * 5 + 10);
Output:
10.0
12.5
In a real program, write Math.random() in place of r, for example int card = (int) (Math.random() * 13) + 1; for a card value from 1 to 13.
Lock it in: memory hooks
- Random int formulaHow many values, times; where to start, plus: (int) (Math.random() * count) + min.
- Return typesOnly abs(int) gives back an int. Everything else on the Math list gives back a double.
Common misconceptions
"Math.pow(2, 3) gives the int 8."
Not quite. pow and sqrt always return a double, even with int arguments. Math.pow(2, 3) is 8.0, and int p = Math.pow(2, 3); does not compile without a cast.
"Math.random() can return 1.0."
Not quite. Math.random() returns a value greater than or equal to 0.0 and less than 1.0. The 1.0 endpoint is exclusive.
"(int) Math.random() * 6 + 1 simulates a die."
Not quite. The cast applies to Math.random() alone, which is always 0 after truncation, so this is always 1. Write (int) (Math.random() * 6) + 1.
"You need to create a Math object first."
Not quite. Math contains only class methods. Call them with the class name: Math.sqrt(2.25).
Exam traps
- (int) Math.random() * 6 is ALWAYS 0, because the cast happens first and (int) of a value below 1.0 is 0. Put parentheses around Math.random() * 6.
- pow and sqrt return a double, even with int arguments, so Math.pow(2, 3) prints 8.0, not 8, and int p = Math.pow(2, 3); does not compile without a cast.
- For a range from min to max inclusive, multiply by max - min + 1, not by max - min.
2PracticeRecall it, then check yourself
In 30 seconds
- Math is in java.lang (no import needed) and has only class methods.
- abs(int) returns an int; abs(double), pow, sqrt and random return a double.
- Math.random() returns a double from 0.0 (inclusive) up to 1.0 (exclusive).
- (int) (Math.random() * (max - min + 1)) + min gives an int from min to max, both inclusive.
- An endpoint is inclusive if it can occur and exclusive if it cannot.
Cover this list, say the points out loud, then take the checkpoint without scrolling back up.
Checkpoint · 4 questions
Checkpoint: Math Class
Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.
3PrevailLock it in for exam day
By the numbers
Key terms: flip the cards
Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.
-
Math classtap to flip
A class in java.lang that contains only class methods for common calculations, such as abs, pow, sqrt and random.
Example and CED codes -
Math.randomtap to flip
A Math class method that returns a double greater than or equal to 0.0 and less than 1.0.
Example and CED codes -
Inclusive and exclusivetap to flip
Describes an endpoint of a range: inclusive means the value can occur, exclusive means it cannot.
Example and CED codes -
Class methodtap to flip
A method associated with the class, not with instances of the class. Its header includes the keyword static.
Example and CED codes -
Packagetap to flip
A group of related classes in an API or library, such as java.lang, which holds String and Math.
Example and CED codes -
Castingtap to flip
Converting a value between double and int with the casting operators (int) and (double).
Example and CED codes
Questions students ask
What Math methods do I need for AP® Computer Science A?
Five, all on the Java Quick Reference: abs(int x), abs(double x), pow(double base, double exponent), sqrt(double x) and random().
How do you get a random integer in a range in Java?
Use (int) (Math.random() * (max - min + 1)) + min. For a die, (int) (Math.random() * 6) + 1 gives an int from 1 to 6, both inclusive.
Does Math.random() include 1.0?
No. Math.random() returns a double greater than or equal to 0.0 and less than 1.0. 0.0 is inclusive and 1.0 is exclusive.
Do I need to import the Math class?
No. Math is in the java.lang package, and classes in java.lang are available by default.