APCSA Class Notes – 1.11 The Math Class

Overview

The Math class in Java is a built-in utility class that provides common mathematical functions. It is part of java.lang, so it does not require an import statement. All methods in the Math class are static, meaning you call them using the class name:

Math.methodName(parameters);

You never create a Math object.


1. Static Methods in the Math Class

A. Square Root – Math.sqrt()

Returns the square root of a number.

double result = Math.sqrt(25); // result = 5.0

B. Powers – Math.pow()

Raises a number to a specific power.

double result = Math.pow(3, 4); // result = 81.0

C. Random Values – Math.random()

Generates a value from 0.0 up to 1.0 (but not including 1.0).

double r = Math.random(); // r is between 0.0 and 1.0

Creating Random Integers

General formula:

(int)(Math.random() * range + start)

Examples:

// Random int 0–9
int num = (int)(Math.random() * 10);

// Random int 1–6 (dice)
int roll = (int)(Math.random() * 6 + 1);

// Random int 5–15
int n = (int)(Math.random() * 11 + 5);

2. Other Important Math Methods

Absolute Value – Math.abs()

int x = Math.abs(-12); // 12

Rounding Methods

Math.round(3.6); // 4
Math.floor(3.6); // 3.0
Math.ceil(3.1);  // 4.0

3. Why APCS A Uses the Math Class

The Math class is used frequently in:


4. Summary Table

Method Purpose Returns Example
Math.sqrt(x) Square root double Math.sqrt(16) → 4.0
Math.pow(a, b) a to the power of b double Math.pow(2, 3) → 8.0
Math.random() Random number 0.0–1.0 double Math.random()
Math.abs(x) Absolute value int/double Math.abs(-5)
Math.round(x) Rounds to nearest long/int Math.round(2.7)
Math.floor(x) Rounds down double Math.floor(2.7)
Math.ceil(x) Rounds up double Math.ceil(2.1)

5. Practice Examples

A. Write the Java expression for:

  1. Square root of 89
    Math.sqrt(89);

  2. 7 to the 3rd power
    Math.pow(7, 3);

  3. Random integer from 1 to 100
    (int)(Math.random() * 100 + 1);

  4. Absolute value of (x − y)
    Math.abs(x - y);