Unit 1.11: Math Class
The Math Class
- The
Mathclass is part of thejava.langpackage, which is automatically imported into every Java program.
Static Utility Class
- The
Mathclass is a utility class that provides common mathematical functions. You never create an "instance" ofMath; you simply call its static methods using the class name.
- The
Mathclass contains only static methods (class methods), meaning they are called using the class name:Math.methodName().
Key Math Methods
The following static methods are part of the Java Quick Reference and are required for the AP CSA exam:
| Method Signature | Description | Result Example |
|---|---|---|
static int abs(int x) |
Returns the absolute value of an int. |
Math.abs(-5) → 5 |
static double abs(double x) |
Returns the absolute value of a double. |
Math.abs(-5.5) → 5.5 |
static double pow(double base, double exponent) |
Returns the value of the base raised to the power of the exponent. |
Math.pow(2, 3) → 8.0 |
static double sqrt(double x) |
Returns the positive square root of a double. |
Math.sqrt(9.0) → 3.0 |
static double random() |
Returns a double value in the range [0.0, 1.0) (inclusive of 0.0, exclusive of 1.0). |
Math.random() → 0.453... |
Generating Random Numbers
By manipulating the result of Math.random(), you can generate random integers within a specific range.
Pseudorandomness
Math.random()returns a decimal between 0.0 and 0.999... By multiplying this value by a range and casting toint, you can generate random whole numbers.
Formula for a random integer between min and max (inclusive):
int randomNum = (int) (Math.random() * range) + min;
- range: The number of possible values, calculated as
max - min + 1. - min: The starting value of your range.

Examples
Using Math Methods
Task: Applying common Math library methods.
double power = Math.pow(10, 2); // Result: 100.0 (double)
double root = Math.sqrt(100); // Result: 10.0 (double)
int val = Math.abs(-50); // Result: 50 (int)
Random Integers
To generate a random number between 1 and 10 (inclusive):
- Calculate the range:
10 (max) - 1 (min) + 1 = 10total values. - Apply the formula:
Task: Generating a random integer within a specific range.
java // Math.random() * 10 gives a value in [0.0, 10.0) // (int) converts it to an integer in [0, 9] // Adding 1 shifts the range to [1, 10] int rand = (int)(Math.random() * 10) + 1;