ACSA Exam Prep
Unit 1 · Using Objects and Methods · Topic 1.11

Math Class

Skill 2.CSkill 4.A

Big idea: The Math class gives you absolute value, powers, square roots, and random numbers. All its methods are static, and most return doubles.

Learning objectives
  • Develop code to write expressions that incorporate calls to built-in mathematical libraries and determine the value that is produced as a result.

The four methods you need

CallReturnsExample
Math.abs(x)Same type as xMath.abs(-7) → 7
Math.pow(base, exp)doubleMath.pow(2, 10) → 1024.0
Math.sqrt(x)doubleMath.sqrt(49) → 7.0
Math.random()double in [0.0, 1.0)0.0 ≤ value < 1.0
Code
System.out.println(Math.abs(-7));
System.out.println(Math.abs(-2.5));
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(49));
System.out.println(Math.sqrt(3 * 3 + 4 * 4));
Output
7
2.5
1024.0
7.0
5.0

Random integers in a range

Math.random() returns a double from 0.0 up to (but not including) 1.0. Multiply to stretch the range, cast to int to drop the fraction, then add to shift it.

For integers from min to max inclusive, there are max - min + 1 possible values:

Code
// int r = (int) (Math.random() * (max - min + 1)) + min;
int die = (int) (Math.random() * 6) + 1;      // 1..6
int r = (int) (Math.random() * 11) + 10;      // 10..20
int coin = (int) (Math.random() * 2);         // 0 or 1
System.out.println(die >= 1 && die <= 6);
System.out.println(r >= 10 && r <= 20);
Output
true
true

Reverse it: what range does this produce?

Exam questions often show the expression and ask for the range. In (int) (Math.random() * N) + K, the smallest value is K and the largest is K + N - 1.

Code
// (int) (Math.random() * 5) + 3   gives 3, 4, 5, 6, 7
// (int) (Math.random() * 10) - 5  gives -5 .. 4
System.out.println(3 + 5 - 1);
Output
7
Key points
  • Math is in java.lang and has only static methods.
  • Math.pow and Math.sqrt always return double.
  • Random int in [min, max]: (int) (Math.random() * (max - min + 1)) + min.
Watch out
  • int x = Math.sqrt(16); does not compile: a double can't go into an int without a cast.
  • Cast the whole product: (int) Math.random() * 6 is always 0.
Exam tip
  • For range questions, plug in the extremes: 0.0 for the smallest and something like 0.999 for the largest.
Quick check
Write an expression for a random int from 5 to 12 inclusive.
Show answer
(int) (Math.random() * 8) + 5, since 12 - 5 + 1 = 8.
What type is Math.pow(3, 2)?
Show answer
double (9.0).