Reference Guide

The Problem: Building a Game Without Math Class

Imagine you’re creating a simple RPG game and you need to:

  • Calculate a player’s damage: 10 x (1.5^level)
  • Find the distance between the player and an enemy
  • Generate random loot drops
  • Round numbers for displaying stats

Key Topics

Term Definition Example
Math class A built-in class of class methods for numeric operations. Part of java.lang, so no import is needed. Math.sqrt(25)
Math.abs(x) Absolute value. Math.abs(-5) -> 5
Math.pow(base, exp) Raises a number to a power. Returns a double. Math.pow(2, 3) -> 8.0
Math.sqrt(x) Nonnegative square root. Returns a double. Math.sqrt(25) -> 5.0
Math.random() A random double, 0.0 inclusive to 1.0 exclusive. Math.random() -> varies
Casting Converting a value from one type to another, such as double to int. (int)(4.9) -> 4

Quick Reference

  • Math is in java.lang, so no import is needed.
  • The Math class contains only class methods, so call them with Math.methodName().
  • Math.abs(x) never returns a value with a smaller magnitude than x.
  • Math.pow and Math.sqrt always return a double, even for whole-number results.
  • Math.random() can return 0.0, but it can never return 1.0.
  • Random values are shaped into a range with arithmetic and a cast, not by Math.random() alone.

Building a Random Range

To get a random integer from min through max, inclusive:

Code Runner Challenge

Run it a few times and watch which line changes

View IPYNB Source
(int)(Math.random() * (max - min + 1)) + min
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
Step What it does to the interval
Math.random() 0.0 up to (not including) 1.0
* (max - min + 1) scales to 0.0 up to (not including) max - min + 1
(int)(...) casts to 0 through max - min (truncates, does not round)
+ min shifts to min through max, inclusive

College Board Requirements

AP CSA Unit 1, Topic 1.11 Math Class. From the course and exam description (College Board, 2025, p. 44): Math “contains only class methods.”

This lesson covers these Topic 1.11 ideas (paraphrased; check exact wording and numbering in the CED):

  • Math is a predefined class in java.lang that contains only class (static) methods, so no import and no Math object are needed.
  • Math.abs(x) returns the absolute value of x.
  • Math.pow(base, exponent) returns base raised to exponent, as a double.
  • Math.sqrt(x) returns the nonnegative square root of x, as a double.
  • Math.random() returns a double in the range 0.0 inclusive to 1.0 exclusive.
  • The result of Math.random() can be scaled and shifted with arithmetic, and cast to int, to produce a random integer within a defined range.

Oracle’s Java SE 25 API documents Math as the standard class for basic numeric operations and specifies the contracts for abs, pow, sqrt, and random (Oracle, 2025), so predictions in this lesson should be based on those return values and ranges.

Lesson Plan

Learning Objective: Use built-in Math class methods in expressions and determine the values they produce.

Success Criteria: Given a Math method call, you can identify what it returns and use it correctly in a Java expression.

Tech Talk

The Math class is part of java.lang, which is available automatically. Its methods are static, so we call them with Math.methodName().

Method What it does Example
Math.abs(int) / Math.abs(double) Absolute value Math.abs(-5) -> 5
Math.pow(double, double) Raises a number to a power Math.pow(2, 3) -> 8.0
Math.sqrt(double) Nonnegative square root Math.sqrt(25) -> 5.0
Math.random() Random double, 0.0 inclusive to 1.0 exclusive Math.random() -> varies

You can combine Math methods in one expression:

Code Runner Challenge

Run it, then change level and the enemy position and predict the new output

View IPYNB Source
double distance = Math.sqrt(Math.pow(3, 2) + Math.pow(4, 2));
System.out.println(distance); // 5.0
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Runner Challenge

Run it a few times. Math.random() changes, but the other three lines never do.

Code Runner Challenge

Run it several times. Confirm "Final roll" is always 1-6, never 0 or 7

View IPYNB Source
// CODE_RUNNER: Run it a few times and watch which line changes
public class MathDemo {
    public static void main(String[] args) {
        System.out.println(Math.abs(-12));   // 12
        System.out.println(Math.pow(2, 3));  // 8.0
        System.out.println(Math.sqrt(25));   // 5.0
        System.out.println(Math.random());   // 0.0 <= value < 1.0, changes each run
    }
}

MathDemo.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Code Examples

A. Math.abs, Math.pow, and Math.sqrt

The GameMath class uses the three non-random methods together to solve a real RPG problem: player damage and the distance to an enemy.

Code Runner Challenge

Run it several times. Confirm the roll is always 10-20, never 9 or 21

View IPYNB Source
double damage = 10 * Math.pow(1.5, level);
double distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Terminology: Math.pow and Math.sqrt always return a double, even when the math result is a whole number, so Math.sqrt(25) prints 5.0, not 5.

Code Runner Challenge

Fill in your predictions, then run it and compare

View IPYNB Source
// CODE_RUNNER: Run it, then change level and the enemy position and predict the new output
public class GameMath {
    public static void main(String[] args) {
        // Damage: 10 * (1.5 ^ level)
        int level = 3;
        double damage = 10 * Math.pow(1.5, level);
        System.out.println("Damage at level " + level + ": " + damage);

        // Distance between the player (0, 0) and an enemy at (3, 4)
        int dx = 3;
        int dy = 4;
        double distance = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
        System.out.println("Distance to enemy: " + distance);

        // abs is useful for health lost, no matter the sign of the change
        int healthChange = -17;
        System.out.println("Health lost: " + Math.abs(healthChange));
    }
}

GameMath.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

B. Building a random range step by step

The RangeBuilder class prints the value after each transformation, so you can see the interval shrink and shift.

Code Runner Challenge

Write your random range from 10-20, then run it several times

View IPYNB Source
(int)(Math.random() * (max - min + 1)) + min
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
Step Interval
Math.random() 0.0 up to (not including) 1.0
* 6 0.0 up to (not including) 6.0
(int)(...) 0 through 5
+ 1 1 through 6

Terminology: The cast to int truncates (cuts off the decimal), it does not round. (int)(4.9) is 4, not 5.

Code Runner Challenge

Finish the loot drop program, then run it a few times

View IPYNB Source
// CODE_RUNNER: Run it several times. Confirm "Final roll" is always 1-6, never 0 or 7
public class RangeBuilder {
    public static void main(String[] args) {
        double step1 = Math.random();              // 0.0 <= step1 < 1.0
        double step2 = step1 * 6;                   // 0.0 <= step2 < 6.0
        int step3 = (int) step2;                    // 0 <= step3 <= 5
        int roll = step3 + 1;                        // 1 <= roll <= 6

        System.out.println("Math.random():      " + step1);
        System.out.println("After * 6:           " + step2);
        System.out.println("After (int) cast:    " + step3);
        System.out.println("Final roll (1-6):    " + roll);
    }
}

RangeBuilder.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

C. A range that does not start at 1

The TenToTwenty class shows the general formula, (int)(Math.random() * (max - min + 1)) + min, for a range that does not start at 1.

Terminology: max - min + 1 is the count of possible whole numbers in the range. For 10 through 20, that is 11 numbers, so multiply by 11.

// CODE_RUNNER: Run it several times. Confirm the roll is always 10-20, never 9 or 21
public class TenToTwenty {
    public static void main(String[] args) {
        int min = 10;
        int max = 20;

        int roll = (int)(Math.random() * (max - min + 1)) + min;
        System.out.println("Roll (10-20): " + roll);
    }
}

TenToTwenty.main(null);

Hacks & Practice Tasks

Popcorn Hack #1

2-minute challenge: predict without running.

  1. Predict the output of the three Math calls below.
  2. Write one Math expression for the distance between (0, 0) and (3, 4).
  3. Run the cell and compare.

Replace every "?" with your own answer.

// CODE_RUNNER: Fill in your predictions, then run it and compare
public class PopcornMath {
    // Predict BEFORE running
    static String guess1 = "?";  // Math.abs(-8)
    static String guess2 = "?";  // Math.pow(3, 2)
    static String guess3 = "?";  // Math.sqrt(36)

    public static void main(String[] args) {
        System.out.println("Predictions: " + guess1 + ", " + guess2 + ", " + guess3);
        System.out.println("Actual:");
        System.out.println(Math.abs(-8));
        System.out.println(Math.pow(3, 2));
        System.out.println(Math.sqrt(36));

        // Distance between (0, 0) and (3, 4)
        double distance = 0; // TODO: replace 0 with a Math expression
        System.out.println("Distance: " + distance);
    }
}

PopcornMath.main(null);

Popcorn Hack #2

Write a program that generates a random integer from 10 through 20, inclusive. Run it several times and confirm it never prints 9 or 21.

Hint: (int)(Math.random() * (max - min + 1)) + min

// CODE_RUNNER: Write your random range from 10-20, then run it several times
public class PopcornRange {
    public static void main(String[] args) {
        int min = 10;
        int max = 20;

        // TODO: replace 0 with the random-range formula
        int roll = 0;
        System.out.println("Roll (10-20): " + roll);
    }
}

PopcornRange.main(null);

MCQ Check

5 questions, one at a time. Answer, check, then go to the next one. At the end, copy your score line (for example 4/5 | answers: B,D,A,C,B) into your notes.

Question 1 of 5

Which import is needed to use Math.sqrt?

  • A. import java.lang.Math;
  • B. import java.util.Math;
  • C. No import needed
  • D. import Math;
Check answer **C.** `Math` is in `java.lang`, which is available automatically in every Java program.

Question 2 of 5

What does Math.pow(4, 0.5) return?

  • A. 2
  • B. 2.0
  • C. 4.5
  • D. A compile error
Check answer **B.** `Math.pow` always returns a `double`, so even though the value is mathematically 2, Java prints `2.0`.

Question 3 of 5

Which value can Math.random() never return?

  • A. 0.0
  • B. 0.5
  • C. 0.999999
  • D. 1.0
Check answer **D.** The range is `0.0` inclusive to `1.0` exclusive, so `1.0` itself is never returned.

Question 4 of 5

Which expression gives a random integer from 5 through 10, inclusive?

  • A. (int)(Math.random() * 5) + 5
  • B. (int)(Math.random() * 6) + 5
  • C. (int)(Math.random() * 10) + 5
  • D. (int)(Math.random() * 5) + 6
Check answer **B.** `max - min + 1` is `10 - 5 + 1 = 6`, so multiply by 6 and add the minimum, 5.

Question 5 of 5

int x = (int)(Math.random() * 6) + 1; is run many times. Which value will never appear?

  • A. 1
  • B. 6
  • C. 7
  • D. 3
Check answer **C.** The cast gives `0` through `5`, and adding 1 gives `1` through `6`. `7` is outside the range.

Homework Hack: Random Loot

Task: Build a random loot drop program.

Requirements

  • Generate a random rarity number from 1-100.
    • 1-60 -> Common
    • 61-85 -> Rare
    • 86-100 -> Legendary
  • Generate a random gold value:
    • Common: 10-30
    • Rare: 31-70
    • Legendary: 71-100
  • Print the rarity roll, rarity, and gold value.
  • You must use Math.random() to generate the random values.

Example Output

Loot Drop!
Rarity Roll: 73
You got: RARE item
Gold Value: 54

The exact output will change each time because the values are random.

// CODE_RUNNER: Finish the loot drop program, then run it a few times
public class RandomLoot {
    public static void main(String[] args) {
        // 1. Random rarity roll, 1-100
        int rarityRoll = 0; // TODO: use the random-range formula

        // 2. Decide the rarity name from the roll
        String rarity = "?"; // TODO: Common / Rare / Legendary

        // 3. Random gold value, range depends on the rarity
        int gold = 0; // TODO: use the random-range formula for the matching rarity

        System.out.println("Loot Drop!");
        System.out.println("Rarity Roll: " + rarityRoll);
        System.out.println("You got: " + rarity + " item");
        System.out.println("Gold Value: " + gold);
    }
}

RandomLoot.main(null);

References

College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf

Oracle. (2025). Math (Java SE 25 & JDK 25) [API documentation]. https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/Math.html

past homework

All Java lessons