Lesson 1.10 · Unit 1 · CED topic 1.11

The Math class

The Math class is the first library class you will use constantly. It holds the common mathematical operations, and it contains only class methods, so every call is written Math.name(...) with no object. The Math class is part of the java.lang package, which is available by default: no import is needed.

Required content · LO 1.11.A

Learning objective.

  • 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.

Essential knowledge.

  • 1.11.A.1. The Math class is part of the java.lang package. Classes in the java.lang package are available by default.
  • 1.11.A.2. The Math class contains only class methods. The following Math class methods—including what they do and when they are used—are part of the Java Quick Reference:
    • static int abs(int x) returns the absolute value of an int value.
    • static double abs(double x) returns the absolute value of a double value.
    • static double pow(double base, double exponent) returns the value of the first parameter raised to the power of the second parameter.
    • static double sqrt(double x) returns the nonnegative square root of a double value.
    • static double random() returns a double value greater than or equal to 0.0 and less than 1.0.
  • 1.11.A.3. The values returned from Math.random() can be manipulated using arithmetic and casting operators to produce a random int or double in a defined range based on specified criteria. Each endpoint of the range can be inclusive, meaning the value is included, or exclusive, meaning the value is not included.

The five methods you need

These are the Math methods on the Java Quick Reference sheet you receive during the exam.

MethodReturnsWhat it does
static int abs(int x)intthe absolute value of an int
static double abs(double x)doublethe absolute value of a double
static double pow(double base, double exponent)doublebase raised to the power exponent
static double sqrt(double x)doublethe nonnegative square root of x
static double random()doublea value greater than or equal to 0.0 and less than 1.0

abs is overloaded: the version that runs depends on the argument type. Note carefully that pow, sqrt, and random always return a double, even when the answer is a whole number.

System.out.println(Math.abs(-7));
System.out.println(Math.abs(-7.5));
System.out.println(Math.pow(2, 10));
System.out.println(Math.sqrt(49));
System.out.println(Math.sqrt(2));
7
7.5
1024.0
7.0
1.4142135623730951

Because pow returns a double, storing its result in an int needs a cast:

int big = (int) Math.pow(2, 10);
System.out.println(big);
1024

Random numbers

Math.random() returns a double in the interval from 0.0 up to but not including 1.0. Each endpoint of a range is either inclusive (the value can occur) or exclusive (it cannot). Here the lower end is inclusive and the upper end exclusive, written [0.0, 1.0).

You turn that one primitive into any range you want with arithmetic and a cast:

  1. Multiply by the number of values you want: Math.random() * 6 is in [0.0, 6.0).
  2. Cast with (int) to truncate: (int) (Math.random() * 6) is one of 0, 1, 2, 3, 4, 5.
  3. Add the smallest value you want: (int) (Math.random() * 6) + 1 is one of 1 through 6.

For integers from min to max inclusive, the formula is:

int value = (int) (Math.random() * (max - min + 1)) + min;

For a double in [a, b), scale by the width and shift: Math.random() * (b - a) + a.

You can test a formula without waiting for random numbers by feeding it values at the edges of the range. Pretend Math.random() returned r:

rr * 6(int) (r * 6)+ 1
0.00.001
0.160.9601
0.171.0212
0.53.034
0.9995.99456

The smallest possible r gives the smallest value and the largest possible r gives the largest, and nothing can produce 7. That is the check to use on any random-range expression.

Worked example · the distance between two points

Find the distance between (1, 2) and (4, 6) with the distance formula.

int x1 = 1;
int y1 = 2;
int x2 = 4;
int y2 = 6;
double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
System.out.println(distance);
5.0

Math.pow(3, 2) is 9.0 and Math.pow(4, 2) is 16.0. Their sum, 25.0, has a square root of 5.0. The int arguments were widened to double because the parameters are double.

Worked example · choosing a range

Write an expression for each description, then check the endpoints.

double r = 0.999;
int roll = (int) (r * 6) + 1;
int age = (int) (r * (65 - 18 + 1)) + 18;
int pick = (int) (r * 10);
System.out.println(roll + " " + age + " " + pick);
6 65 9
DescriptionExpressionSmallestLargest
a die roll, 1 to 6(int) (Math.random() * 6) + 116
an age from 18 to 65 inclusive(int) (Math.random() * 48) + 181865
a digit, 0 to 9(int) (Math.random() * 10)09

The 48 comes from 65 - 18 + 1, the number of values in an inclusive range. Forgetting the + 1 is the classic off-by-one mistake: it silently makes the top value impossible.

Worked example · mixed calls and types

Evaluate each statement, noting the type of each result.

int a = Math.abs(-12) + 3;
double b = Math.abs(-12.0) + 3;
double c = Math.pow(3, 2) / 2;
int d = (int) Math.sqrt(30);
System.out.println(a + " " + b + " " + c + " " + d);
15 15.0 4.5 5

Math.abs(-12) uses the int version and returns 12, so a is the int 15. With a double argument the result is a double. Math.pow(3, 2) is 9.0, and 9.0 / 2 is 4.5. Math.sqrt(30) is about 5.477, and the cast truncates it to 5.

Exam focus

Expect the exam to ask for the range of an expression that uses Math.random() (what are the smallest and largest values it can produce, and which are possible) and to ask you to complete a random expression for a stated range. Check the endpoints with the table method. Remember the return types: pow, sqrt, and random return double, and abs returns whatever type it was given. The Math methods on the Java Quick Reference are all you can assume.

Practice
  1. What is printed?
    System.out.println(Math.abs(3 - 10));
    System.out.println(Math.pow(5, 2));
    Show answer

    7 and 25.0. The absolute value of -7 is 7 (an int), and Math.pow returns a double, so 25 prints as 25.0.

  2. Which expression produces an int from 1 to 10 inclusive?
    A.  (int) (Math.random() * 10)
    B.  (int) (Math.random() * 10) + 1
    C.  (int) (Math.random() * 11)
    D.  (int) (Math.random() * 10 + 1.0) + 1
    Show answer

    B. Math.random() * 10 is in [0.0, 10.0), the cast gives 0 through 9, and adding 1 gives 1 through 10. A gives 0 to 9, C gives 0 to 10, and D gives 1 to 11.

  3. What is the smallest and largest value that (int) (Math.random() * 5) + 3 can produce?
    Show answer

    Smallest 3, largest 7. The cast part is 0 through 4, and the shift of 3 gives 3 through 7. There are five possible values.

  4. Write a statement that stores the cube root idea x squared in an int named sq when x is the int 9, using Math.pow.
    int x = 9;
    int sq = (int) Math.pow(x, 2);
    System.out.println(sq);
    Show answer

    int sq = (int) Math.pow(x, 2);. The cast is required because Math.pow returns a double, which cannot be stored in an int without one.

  5. What is printed?
    double r = 0.5;
    System.out.println((int) (r * 4) + 10);
    System.out.println(r * 4 + 10);
    Show answer

    12 and 12.0. In the first line, (int) (r * 4) is (int) 2.0, or 2, and adding 10 gives the int 12. The second line never casts, so the sum stays a double.

  6. Why does this code not compile, and how do you fix it?
    int root = Math.sqrt(16);
    Show answer

    Math.sqrt returns a double, and a double cannot be stored in an int without a cast (a possible lossy conversion). Fix it with int root = (int) Math.sqrt(16); or store the result in a double.

← 1.9 Calling class methods1.11 Objects, classes, and constructors →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course