The Java
Math Class
Master the static methods of java.lang.Math: absolute value, exponents, square roots, and random numbers for the AP exam.
What Is the Math Class?
Java provides a built-in class called Math in the java.lang package. It contains static methods for common mathematical operations: you never create a Math object: you call each method directly on the class itself.
Why the Math Class Matters
The Four Key Methods
Math.abs: Absolute Value
Math.abs(x) returns the absolute value of \( x \). It is overloaded: passing an int returns an int; passing a double returns a double.
Math.pow: Exponentiation
Math.pow(base, exponent) returns \( \text{base}^{\text{exponent}} \). Both parameters are doubles and it always returns a double: even \( 2^3 \) returns 8.0, not 8.
Math.sqrt: Square Root
Math.sqrt(x) returns \( \sqrt{x} \) as a double. Passing a negative value returns NaN (Not a Number).
Math.random: Random Numbers
Math.random() returns a double \( d \) such that \( 0.0 \leq d < 1.0 \). To generate integers in a range, you scale and cast.
int vs double Return Types
| Method | Parameter | Return Type |
|---|---|---|
| Math.abs(int) | int | int |
| Math.abs(double) | double | double |
| Math.pow(double, double) | double, double | double |
| Math.sqrt(double) | double | double |
| Math.random() | none | double |
How to Apply the Math Class
Example 1: Distance Between Points
Find the distance between \( (1, 2) \) and \( (4, 6) \) using the distance formula: \( d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2} \).
Example 2: Random Range
Generate a random integer between 10 and 50 (inclusive).
A tabletop dice experiment linked to its full outcome space
A die roll can be generated with (int)(Math.random() * 6) + 1. Two independently generated rolls form an ordered pair of values from 1 through 6.Two dice, 36 ordered outcomes
For two independent fair dice, six of the 36 equally likely ordered pairs sum to seven, so P(sum = 7) = 1/6. The red die supplies the row and the ivory die the column.Example 3: Combining Methods
What is the output of the following code?
Common Mistakes
Summary Reference Table
| Call | Returns | Example |
|---|---|---|
| Math.abs(-7) | 7 | int |
| Math.abs(-3.5) | 3.5 | double |
| Math.pow(2, 10) | 1024.0 | double |
| Math.sqrt(144) | 12.0 | double |
| Math.random() | \([0.0, 1.0)\) | double |
| (int)(Math.random()*6)+1 | \([1, 6]\) | int |
Question 1 of 5
What is the value of Math.abs(-12)?
Question 2 of 5
What does Math.pow(3, 2) return?
Question 3 of 5
Which expression generates a random int from 5 to 15 (inclusive)?
Question 4 of 5
What is the output of the following code?
double x = Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2));
System.out.println((int) x);
Question 5 of 5
Which statement about the Math class is false?