AP Computer Science A · Study guide

Math Class

AP® Computer Science A · Using Objects and Methods

The Math Class

The class methods every Java program can use for calculation: absolute value, powers, square roots, and random numbers, with careful attention to their return types and to turning Math.random into a random value in any range.

Big Picture

The Math class is part of the java.lang package, so it is available in every program without an import. It contains only class methods, which are called with the class name: Math.abs, Math.pow, Math.sqrt, and Math.random. Most of them return a double, which affects how results print and where they can be stored. Math.random returns a double from 0.0 up to but not including 1.0, and arithmetic plus casting turns it into a random number in any range you need.

1A Class Made of Class Methods

The Math class contains only class methods. There are no Math objects to create; every method takes what it needs through its parameters and returns a result. Calls always take the form Math.methodName(arguments), and because Math belongs to java.lang, no import statement is required.

Five methods form the core toolbox. abs comes in two overloaded versions, one for int and one for double. pow, sqrt, and random each have a single version, and all three return a double. Knowing each method's parameter types and return type is what lets you predict printed output and avoid compile errors.

Figure 1. The Math class contains only class methods. Apart from abs(int), every one of these returns a double.
MethodParametersReturns
static int abs(int x)One intThe absolute value of x, as an int
static double abs(double x)One doubleThe absolute value of x, as a double
static double pow(double base, double exponent)Two doublesbase raised to the power exponent
static double sqrt(double x)One double (non-negative)The non-negative square root of x
static double random()NoneA double from 0.0 up to but not including 1.0
Common Mistake 1 · Creating a Math Object

Math m = new Math(); does not compile. The Math class is used only through its class methods: write Math.sqrt(25), never m.sqrt(25).

2Absolute Value

The absolute value of a number is its distance from zero: −7 and 7 both have absolute value 7. Math.abs(int x) returns an int, and Math.abs(double x) returns a double. Java picks the version that matches the argument, so Math.abs(-7) prints 7 while Math.abs(-7.0) prints 7.0.

Absolute value is the natural tool for measuring how far apart two values are regardless of order. The difference between a guess and a target, Math.abs(guess - target), is the same whether the guess was too high or too low, which makes it ideal for comparisons such as "within 5 of the target."

Worked Example 1 Math.abs

Absolute Value for int and double

Predict each result and notice its type.

Code
System.out.println(Math.abs(-7));
System.out.println(Math.abs(-7.25));
System.out.println(Math.abs(3 - 8));
System.out.println(Math.abs(12));
Output
7
7.25
5
12
  1. 1Math.abs(-7). The int version runs and returns the int 7.
  2. 2Math.abs(-7.25). The double version returns 7.25.
  3. 3Math.abs(3 - 8). The argument is evaluated first: −5, so the result is 5.
  4. 4Math.abs(12). A non-negative value is returned unchanged.
Result: The results are 7, 7.25, 5, and 12. Math.abs is overloaded: the int version returns an int and the double version returns a double.

3Powers and Square Roots

Math.pow(double base, double exponent) returns the value of the first parameter raised to the power of the second. Math.sqrt(double x) returns the non-negative square root of its argument. Both take double parameters, so int arguments are widened automatically, and both return a double, so even whole-number answers print with a decimal point: Math.pow(2, 3) is 8.0 and Math.sqrt(49) is 7.0.

Exponents can be zero, negative, or fractional: Math.pow(5, 0) is 1.0, Math.pow(2, -1) is 0.5, and Math.pow(9, 0.5) is 3.0. Results that are irrational, such as Math.sqrt(2), are approximations stored in a double, so they carry the usual round-off. Math calls can be nested, with inner calls evaluated first, which makes formulas such as the Pythagorean theorem a single line of code.

Figure 2. Math.pow and Math.sqrt always return a double, even when the answer is a whole number.
Worked Example 2 pow and sqrt

Powers and Square Roots

Predict each output.

Code
System.out.println(Math.pow(2, 10));
System.out.println(Math.pow(5, 0));
System.out.println(Math.pow(2, -1));
System.out.println(Math.sqrt(144));
System.out.println(Math.sqrt(2));
Output
1024.0
1.0
0.5
12.0
1.4142135623730951
  1. 1Math.pow(2, 10). 2 to the 10th power is 1024, returned as the double 1024.0.
  2. 2Math.pow(5, 0). Any nonzero base to the power 0 is 1, so 1.0.
  3. 3Math.pow(2, -1). A negative exponent means a reciprocal: 1/2 = 0.5.
  4. 4Math.sqrt(144). 12.0, a double even though the root is whole.
  5. 5Math.sqrt(2). An irrational root is approximated to about 16 significant digits.
Result: The outputs are 1024.0, 1.0, 0.5, 12.0, and 1.4142135623730951. pow and sqrt always return a double.
Worked Example 3 Combining methods

The Length of a Diagonal

A rectangular garden bed is 5 m by 12 m. Use the Pythagorean theorem, c = √(a² + b²), to compute the diagonal.

Code
double a = 5;
double b = 12;
double diagonal = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
System.out.println(diagonal);
Output
13.0
  1. 1Inner calls first. Math.pow(a, 2) is 25.0 and Math.pow(b, 2) is 144.0.
  2. 2Add. 25.0 + 144.0 = 169.0.
  3. 3Square root. Math.sqrt(169.0) is 13.0.
  4. 4Alternative. a * a + b * b works just as well for squaring; Math.pow is most useful for exponents other than 2.
Result: The diagonal is 13.0 m. Math methods nest naturally: the result of one call can be the argument of another.
Worked Example 4 Return types

Storing a pow Result in an int

Why does this fail, and how can it be fixed?

Code that does not compile
int side = 4;
int area = Math.pow(side, 2);
System.out.println(area);
Fixed
int side = 4;
int area = (int) Math.pow(side, 2);
System.out.println(area);
Output
16
  1. 1The return type is double. Math.pow(4, 2) returns 16.0.
  2. 2Narrowing needs a cast. Storing a double in an int could lose information, so Java refuses: "possible lossy conversion from double to int."
  3. 3The fix. Cast the result with (int), or store it in a double variable. For simple squares, side * side keeps everything as int with no cast needed.
Result: The first version does not compile; the fixed version prints 16. Always check the return type of a Math method before choosing the variable that stores its result.
Common Mistake 2 · Expecting pow or sqrt to Return an int

Math.pow and Math.sqrt return double values. int x = Math.sqrt(16); does not compile, and System.out.println(Math.pow(3, 2)); prints 9.0, not 9. Store the result in a double, or cast it explicitly when a whole number is guaranteed.

4Math.random

Math.random() takes no arguments and returns a double value greater than or equal to 0.0 and less than 1.0. The lower end, 0.0, is a possible result; the upper end, 1.0, is never returned. Each call produces a new value, so a program that uses Math.random can behave differently every time it runs.

Random numbers let programs simulate chance events such as coin flips, dice, and shuffled cards, and they make games and simulations unpredictable. The raw value is rarely useful by itself, but it is the starting point for every random value you will build: scaling, casting, and shifting transform the interval [0.0, 1.0) into whatever range a program needs.

Figure 3. Math.random() returns a double that is greater than or equal to 0.0 and less than 1.0.

5Random Values in a Defined Range

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. For integers, follow three steps. Scale: multiply by the number of possible values, giving a double from 0.0 up to that number. Truncate: cast to int, giving the whole numbers from 0 up to one less than that number. Shift: add the smallest value you want.

For integers from min to max inclusive, there are max - min + 1 possible values, so the general form is (int) (Math.random() * (max - min + 1)) + min. For a random double in a range, skip the cast: Math.random() * width + start gives values from start up to but not including start + width. To check any expression, substitute the smallest and largest possible values of Math.random() and evaluate.

Figure 4. Math.random can be manipulated with arithmetic and casting to produce a random int in a defined range: scale, truncate, then shift.
Goal (inclusive)Number of valuesExpression
1 to 66(int) (Math.random() * 6) + 1
0 to 910(int) (Math.random() * 10)
10 to 2011(int) (Math.random() * 11) + 10
−5 to 511(int) (Math.random() * 11) - 5
min to maxmax − min + 1(int) (Math.random() * (max - min + 1)) + min
Worked Example 5 Random integers

Checking the Range of a Random Expression

The expression (int) (Math.random() * 6) + 1 simulates a die. Check its smallest and largest possible values by substituting the smallest and largest values Math.random() can return (0.0, and the largest double below 1.0, which is 0.9999999999999999).

Code
double low = 0.0;
double high = 0.9999999999999999;
System.out.println((int) (low * 6) + 1);
System.out.println((int) (high * 6) + 1);
Output
1
6
  1. 1Smallest. 0.0 × 6 = 0.0; cast gives 0; plus 1 gives 1.
  2. 2Largest. Just below 1.0 times 6 is just below 6.0; the cast truncates to 5; plus 1 gives 6.
  3. 3Every value between. The scaled value lands in one of six equal-width slices, [0, 1), [1, 2), …, [5, 6), so each of 1 through 6 is equally likely.
Result: The range is 1 to 6, inclusive. Testing the two extremes is a quick, reliable way to check any random-range expression.
Worked Example 6 Designing ranges

Writing Expressions for Given Ranges

Write an expression that produces a random int in each range, inclusive.

  1. 0 to 9
  2. 10 to 20
  3. −5 to 5
  4. A random double from 2.0 up to but not including 7.0
  1. 1The pattern. For integers from min to max inclusive, there are max - min + 1 possible values: (int) (Math.random() * (max - min + 1)) + min.
  2. 20 to 9. 10 values starting at 0: (int) (Math.random() * 10).
  3. 310 to 20. 11 values starting at 10: (int) (Math.random() * 11) + 10.
  4. 4−5 to 5. 11 values starting at −5: (int) (Math.random() * 11) - 5.
  5. 5A double from 2.0 to 7.0. No cast: the width is 5.0 and the start is 2.0, so Math.random() * 5 + 2.
Result: Count the values to find the multiplier, then add the smallest value. For a double range, multiply by the width and add the start, with no cast.
Worked Example 7 Random in a program

A Random Coin and Die

Each run of this program prints different values. Which values are possible on each line?

Code
int coin = (int) (Math.random() * 2);
int die = (int) (Math.random() * 6) + 1;
double angle = Math.random() * 360;
System.out.println(coin);
System.out.println(die);
System.out.println(angle);

Output varies from run to run; one run might print 1, then 4, then 217.48390125591034.

  1. 1coin. Math.random() * 2 is from 0.0 to just below 2.0; the cast gives 0 or 1.
  2. 2die. 1 through 6, as checked in the previous example.
  3. 3angle. A double from 0.0 up to but not including 360.0, with no cast, so it has a fractional part.
Result: coin is 0 or 1, die is 1 to 6, and angle is a double in [0.0, 360.0). Each call to Math.random() produces a new value.
Common Mistake 3 · Off-by-One Ranges

To include both 1 and 10, the multiplier must be 10, the number of values, not 9 (which would give 1 to 9) or 11 (which would give 1 to 11). Count the values with max - min + 1, and check the extremes before trusting the expression.

6Common Errors With Math Methods

Most Math mistakes involve types or parentheses. A cast applies only to the value immediately after it, so (int) Math.random() * 10 casts the random value first, which always gives 0, and the result is always 0. The parentheses in (int) (Math.random() * 10) make the cast apply after scaling, which is what you want.

Other frequent problems: storing a double result in an int without a cast, forgetting that Math.pow takes the base first and the exponent second, and expecting Math.random() to reach 1.0. Reading each method's signature and return type before using it prevents nearly all of them.

ExpressionPossible resultsWhy
Math.random() * 10double from 0.0 to just below 10.0Scales the range; no cast, so fractions remain
(int) Math.random() * 10Always 0The cast applies to Math.random() first, giving 0, then 0 × 10
(int) (Math.random() * 10)0 to 9Parentheses make the cast apply after scaling
(int) (Math.random() * 10) + 11 to 10Shift by the smallest value
Common Mistake 4 · Casting Math.random Before Scaling

(int) Math.random() * 6 + 1 always evaluates to 1, because (int) Math.random() is always 0. Put parentheses around the multiplication so the cast happens after scaling: (int) (Math.random() * 6) + 1.

Four Habits for the Math Class

1. Call Through the Class

Math.abs, Math.pow, Math.sqrt, Math.random; no objects, no import.

2. Check the Return Type

Only abs(int) returns an int; the rest return double.

3. Count, Then Shift

Multiply by max − min + 1, cast, then add min.

4. Test the Extremes

Substitute 0.0 and just under 1.0 to check a random range.

Core Synthesis

The Math class is part of the java.lang package and contains only class methods. Math.abs(int) returns an int absolute value and Math.abs(double) a double one; Math.pow(double, double) returns the first parameter raised to the power of the second; Math.sqrt(double) returns the non-negative square root; and Math.random() returns a double greater than or equal to 0.0 and less than 1.0. 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.