Java's Math class gives you static methods for common calculations: Math.abs, Math.pow, Math.sqrt and Math.random. pow, sqrt and random always return a double, while abs returns the same type it is given. For a random int from low to high, use (int) (Math.random() * (high - low + 1)) + low, which can produce high - low + 1 different values.
Quick check
What is the value of (int) 7.9 in Java?Show answerHide answer
- Casting a
doubletointdrops the fractional part; it does not round.
- Casting a
Math.sqrt(16) is a static method call. What is the class name in it, and what is the method name?Show answerHide answer
The class is
Mathand the method issqrt. A static method is called on its class name.
Know these already? Jump to the practice questions
What you'll be able to do
- State the return type of
Math.abs,Math.pow,Math.sqrtandMath.random. - Predict what code that calls these methods prints, including the
.0on adouble. - Explain why
Math.random()can return 0.0 but never 1.0. - Write an expression for a random
intin a given range. - Determine the smallest value, the largest value and the number of values a random expression can produce.
Key terms
Absolute value
The distance of a number from zero: the absolute value of -7 is 7, and of 2.5 is 2.5.
- In plain English
- The number with its minus sign removed.
- Don't write
- "
Math.abs(-2.5)returns 2."
Exclusive upper bound
A limit that values can come as close to as you like but never reach. Math.random() has an exclusive upper bound of 1.0.
- In plain English
- "Up to but not including."
- Don't write
- "
Math.random()can return 1.0."
Inclusive range
A range that contains both of its end values. The integers from 5 to 12 inclusive are 5, 6, …, 12: 8 values.
- In plain English
- Both ends count.
- Don't write
- "There are 12 − 5 = 7 integers from 5 to 12."
What do abs, pow and sqrt return?
All four Math methods are static, so you call them on the class name Math, and all four are on the Java Quick Reference.
| Header | Example | Result |
|---|---|---|
int abs(int x) | Math.abs(-7) | 7 |
double abs(double x) | Math.abs(-2.5) | 2.5 |
double pow(double base, double exponent) | Math.pow(2, 10) | 1024.0 |
double sqrt(double x) | Math.sqrt(49) | 7.0 |
abs is overloaded: an int argument runs the int version, so the result is an int, and a double argument runs the double version. pow and sqrt have only double parameters, so an int argument is widened to a double, and the result is always a double. pow(base, exponent) raises the first argument to the power of the second, and sqrt returns the positive square root.
Key idea
pow and sqrt return a double even when every argument is an int.
Check yourself
Show answerHide answer
Math.abs(-4) returns the int 4; Math.sqrt(4) returns the double 2.0.
How do you store and print the results?
A double prints with a decimal point, so System.out.println(Math.sqrt(16)); prints 4.0. To store a double result in an int variable you need a cast: int x = Math.pow(2, 3); does not compile, but int x = (int) Math.pow(2, 3); stores 8. A cast drops the fractional part, so (int) Math.sqrt(20) is 4, because the square root of 20 is about 4.47.
Arguments are worked out before the method runs. In Math.sqrt(9 / 2), the argument 9 / 2 is int division, which gives 4, so the call returns 2.0, not the square root of 4.5.
Check yourself
Show answerHide answer
Math.pow(3, 2)is 9.0, the cast makes it theint9, and 9 + 1 is 10.
What does Math.random return?
Math.random() takes no arguments and returns a double r with 0.0 ≤ r < 1.0. Each call gives a new pseudorandom value, and values are spread about evenly across that range. The result differs from run to run, so questions on random code ask about every possible result: the smallest, the largest, how many, or a value that cannot appear.
Multiplying stretches the range and adding shifts it:
| Expression | Possible values |
|---|---|
Math.random() | 0.0 up to but not including 1.0 |
Math.random() * 6 | 0.0 up to but not including 6.0 |
Math.random() * 6 + 2 | 2.0 up to but not including 8.0 |
Check yourself
Show answerHide answer
No. Math.random() never returns 1.0, so the product always stays below 10.0.
How do you make a random int in a range?
To get a random int from low to high inclusive:
- Count the values:
high - low + 1. - Multiply
Math.random()by that count: 0.0 up to but not including the count. - Cast to
int: the whole numbers 0 to count − 1. - Add
low: the whole numberslowtohigh.
For a die, 1 to 6, that is (int) (Math.random() * 6) + 1. The cast must cover the whole product, so the multiplication goes in its own parentheses. The recipe is not on the Java Quick Reference, only Math.random is: Learn this.
Reading a given expression works the same way in reverse: (int) (Math.random() * k) + c produces k values, from c to c + k − 1.
Check yourself
Show answerHide answer
10, 11, 12 and 13: 4 values, from 10 to 10 + 4 − 1.
Worked example 1: Trace abs, pow and sqrt
Question: What is printed?
int a = -3;
double b = Math.pow(a, 2);
double c = Math.sqrt(b + 16);
int d = Math.abs(a) + (int) c;
System.out.println(b + " " + c + " " + d);
What tells you the method
Each line stores one result, so trace the variables and note each type.
Step 1: Trace each variable.
Line Call Value stored Type 2 Math.pow(-3, 2)9.0 double3 Math.sqrt(25.0)5.0 double4 Math.abs(-3)+(int) 5.08 intWhypowandsqrtreturndoublevalues;absgets anint, so it returns theint3.Step 2: Build the printed line.
The
+joins each value to a space, so the line is 9.0, a space, 5.0, a space, 8.WhyA
doubleprints with.0; anintdoes not.
Check it
(-3)² is 9 and 9 + 16 is 25, whose square root is 5, so the numbers agree with ordinary arithmetic.
Answer
9.0 5.0 8
Worked example 2: Design a random range
Question: A game needs a random int from 5 to 12 inclusive. Build the expression from Math.random(), then state how many different values it can produce.
What tells you the method
A random int in a range, so follow the four-step recipe and test both ends.
Step 1: Count the values.
12 − 5 + 1 = 8.
WhyBoth 5 and 12 are included, so subtracting alone would miss one value.
Step 2: Scale, cast and shift.
Math.random() * 8is 0.0 up to but not including 8.0; the cast gives 0 to 7; adding 5 gives 5 to 12. The expression is(int) (Math.random() * 8) + 5.WhyThe cast cuts each
doubledown to a whole number before the shift.
Check it
Test both ends. If Math.random() returns 0.0, the result is 0 + 5 = 5. If it returns 0.999, the product is 7.992, the cast gives 7 and the result is 12.
Answer
(int) (Math.random() * 8) + 5, which can produce 8 values.
Worked example 3: Spot the correct die roll
Question: A method must return a random int from 1 to 6 inclusive, each value possible. Which return statement does this?
- A)
return (int) Math.random() * 6 + 1; - B)
return (int) (Math.random() * 6); - C)
return (int) (Math.random() * 6) + 1; - D)
return (int) (Math.random() * 5) + 1;
What tells you the method
Each option is a random expression, so find the smallest and largest value of each.
Step 1: Check where each cast applies.
In A, the cast applies to
Math.random()alone, which always becomes 0, so A always returns 0 × 6 + 1 = 1.WhyA cast applies only to the value just after it unless parentheses widen it.
Step 2: Find each range.
B gives 0 to 5; C gives 0 to 5 shifted to 1 to 6; D gives 0 to 4 shifted to 1 to 5.
Why(int) (Math.random() * k) + cgives c to c + k − 1.
Check it
For C, 1 + 6 − 1 = 6, so the top value is 6 and the count is 6, one for each face.
Answer
C
Your turn
Question: What value does x hold after this statement runs?
int x = (int) Math.sqrt(30) + Math.abs(-4) / 3;
Step 1: Work out the cast.
Math.sqrt(30)is about 5.477, and the cast drops the fraction, giving 5.Step 2: Your go: evaluate
Math.abs(-4) / 3, then add.
Show the full solutionHide the solution
Step 2. Math.abs(-4) returns the int 4, and 4 / 3 is int division, which gives 1. Division happens before addition, so x is 5 + 1.
Answer: 6
Traps
Trap
(int) Math.random() * 6 + 1 gives a random number from 1 to 6.
It seems right because the cast looks as if it covers the whole expression. But a cast applies only to the value right after it, so Math.random() is cut to 0 first and the result is always 1. Write (int) (Math.random() * 6) + 1.
What does (int) Math.random() * 10 evaluate to?
0, every time: the cast turns Math.random() into 0 before the multiplication.
Trap
Math.pow(2, 3) returns the int 8 because both arguments are int values.
It seems right because 2 cubed is a whole number. But pow always returns a double, so it is 8.0, prints as 8.0, and needs a cast to go into an int variable.
Does int n = Math.pow(2, 3); compile?
No. Math.pow returns a double, so storing it in an int needs (int).
What's examined
On the AP® Computer Science A exam (Unit 1), Math.abs, Math.pow, Math.sqrt and Math.random are on the Java Quick Reference, but the return types and the random-range recipe are yours to apply. Multiple-choice questions ask what an expression prints or which values a random expression can produce, and free-response code can call these methods.
Practice questions
- Recall Which call returns an
int?
- A)
Math.abs(-9) - B)
Math.pow(3, 2) - C)
Math.sqrt(9) - D)
Math.abs(-9.0)
Show answer
Answer: A. An int argument runs the int version of abs, which returns an int.
Why the others are wrong:
- B:
powalways returns adouble, even withintarguments. - C:
sqrtalways returns adouble. - D: a
doubleargument runs thedoubleversion ofabs.
- Apply What is printed?
System.out.println(Math.pow(2, 3) + Math.abs(-1));
Show answer
Answer: 9.0
Marking points:
Math.pow(2, 3)is thedouble8.0, andMath.abs(-1)is theint1.- A
doubleplus anintis adouble, so the sum is 9.0.
- Apply For the expression
(int) (Math.random() * 10) + 3, give (a) the number of different values it can produce and (b) the largest value.
Show answer
Answer: (a) 10 (b) 12
Marking points:
- The cast gives 0 to 9, which is 10 values.
- Adding 3 gives 3 to 12, so the largest is 9 + 3 = 12.
- Exam-style Which expression gives a random
intfrom -3 to 3 inclusive, with every value possible?
- A)
(int) (Math.random() * 6) - 3 - B)
(int) (Math.random() * 7) + 3 - C)
(int) Math.random() * 7 - 3 - D)
(int) (Math.random() * 7) - 3
Show answer
Answer: D. There are 3 − (−3) + 1 = 7 values; the cast gives 0 to 6, and subtracting 3 gives -3 to 3.
Why the others are wrong:
- A counts 3 − (−3) = 6 values and forgets the + 1, so it gives -3 to 2.
- B shifts the wrong way, giving 3 to 9.
- C casts
Math.random()alone, so it always gives -3.
- Exam-style The method should return the distance between the points (x1, y1) and (x2, y2), the square root of dx² + dy². Give the number of the line that stops it working.
1: public static double distance(int x1, int y1, int x2, int y2)
2: {
3: int dx = x2 - x1;
4: int dy = y2 - y1;
5: double sum = Math.pow(dx, 2) + Math.pow(dy, 2);
6: return Math.pow(sum, 2);
7: }
Show answer
Answer: Line 6.
Marking points:
- Line 6 squares the sum instead of taking its square root:
distance(0, 0, 3, 4)returns 625.0, not 5.0. - The fix is
return Math.sqrt(sum);.
- Apply Which value can
(int) (Math.random() * 5) * 2 + 1never produce?
- A) 1
- B) 10
- C) 9
- D) 5
Show answer
Answer: B. The cast gives 0 to 4, so the expression gives 1, 3, 5, 7 or 9: always odd, never 10.
Why the others are wrong:
- A: 1 comes from a cast result of 0, which happens whenever
Math.random()is below 0.2. - C: 9 comes from a cast result of 4; it is the largest value, not one that is left out.
- D: 5 comes from a cast result of 2.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Call these methods on the class name:
Math.abs,Math.pow,Math.sqrt,Math.random. abskeeps the argument's type;pow,sqrtandrandomgive adouble.Math.random()gives 0.0 up to but not including 1.0.- A random
intfromlowtohighis(int) (Math.random() * (high - low + 1)) + low. (int) (Math.random() * k) + cproduces k values, from c to c + k − 1.