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.

1.11.A1.11.A.11.11.A.21.11.A.3

Reviewed against the CED on

Know this already? Jump to the checkpoint.

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

  1. Math is in java.lang (no import needed) and has only class methods.
  2. abs(int) returns an int; abs(double), pow, sqrt and random return a double.
  3. Math.random() returns a double from 0.0 (inclusive) up to 1.0 (exclusive).
  4. (int) (Math.random() * (max - min + 1)) + min gives an int from min to max, both inclusive.
  5. 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.

  1. 1 What is printed? 1.11.A.2
    System.out.println(Math.abs(-7)
                       + Math.sqrt(16)
                       + Math.pow(2, 3));
    Show answer

    Answer: B. 7 + 4.0 + 8.0: sqrt and pow return doubles, so the sum is the double 19.0. A forgets that the result is a double. C subtracts the absolute value instead of adding it. D writes the parts 7, 4 and 8 side by side as if + glued them together. No String is involved, so + adds numbers (and gluing text would give 74.08.0 anyway).

  2. 2 Which expression produces a random int from 10 to 20, inclusive? 1.11.A.3
    Show answer

    Answer: C. Math.random() * 11 gives 0.0 up to, but not including, 11.0; the cast gives 0 to 10; plus 10 gives 10 to 20. A gives 10 to 19. B is always 10, because the cast applies to Math.random() alone. D gives 10 to 29.

  3. 3 Consider the following code segment. What is printed? 1.11.A.2
    double a = Math.abs(-2.5);
    double b = Math.pow(a, 2);
    System.out.println(Math.sqrt(b));
    Show answer

    Answer: A. a is 2.5, b is 6.25, and the non-negative square root of 6.25 is 2.5. B prints b instead of its square root. C forgets that abs and sqrt never give negative results here. D treats the double result as an int.

  4. 4 A program needs a random double that is at least 5.0 and less than 8.0. Which expression produces it? 1.11.A.3
    Show answer

    Answer: D. Math.random() * 3 gives 0.0 up to 3.0 (exclusive), and adding 5 shifts it to 5.0 up to 8.0. A gives 5.0 up to 13.0. B gives only the ints 5, 6 and 7. C gives 3.0 up to 8.0.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Math methods on the Java Quick Reference five methods CED 1.11.A.2
    1. static int absint x
    2. static double absdouble x
    3. static double powdouble base, double exponent
    4. static double sqrtdouble x
    5. static double random()

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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure