APrep Open the app

AP Computer Science A · Unit 1: Using Objects & Methods

1.13 Using the Math Class

The Math Class

The Math class is part of java.lang and never needs importing. It provides static methods, meaning you call them directly on the class name, like `Math.pow(2, 3)`, instead of creating a Math object. Common methods include `Math.abs()`, `Math.pow()`, `Math.sqrt()`, and `Math.random()`.

Key Math Methods

`Math.abs(x)` returns the absolute value of x. `Math.pow(base, exp)` returns base raised to exp as a double. `Math.sqrt(x)` returns the square root of x as a double. `Math.max(a, b)` and `Math.min(a, b)` return the larger or smaller of two values.

Generating Random Numbers

`Math.random()` returns a double between 0.0 (inclusive) and 1.0 (exclusive). To get a random integer in a range, use the formula `(int)(Math.random() * range) + min`, where range is (max - min + 1). This scales and shifts the random double into the desired integer range.

Key terms

Math.abs(x)
Returns the absolute value of x.
Math.pow(base, exp)
Returns base raised to the power of exp, as a double.
Math.sqrt(x)
Returns the square root of x, as a double.
Math.random()
Returns a random double d where 0.0 <= d < 1.0.
Random integer formula
(int)(Math.random() * range) + min, where range = max - min + 1.

Try an AP-style question

Which expression produces a random integer from 1 to 6 inclusive?

  1. (int) (Math.random() * 6) + 1
  2. Math.random(1, 6)
  3. (int) (Math.random() * 7)
  4. (int) Math.random() * 6 + 1
Show the answer

A. Scale, truncate, shift.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 1.13 free in APrep