Unit 1 Cycle 2 Day 19: Spotting the Error: Math Methods

Unit 1 Advanced (Cycle 2) Day 19 of 28 Advanced

Spotting the Error: Math Methods

Section 1.13 — The Math Class

Key Concept

Error-spotting with Math class methods tests your knowledge of return types and valid arguments. Math.pow(2, 3) returns 8.0 (a double), not 8. Math.sqrt(-1) returns NaN, not an error. Math.abs(Integer.MIN_VALUE) overflows and returns a negative number. Math.random() takes no arguments. The AP exam creates code where a Math method return value is assigned to an incompatible type or used in a context that assumes the wrong type.

A student writes the following code. Which line contains an error?

Line 1: Math m = new Math(); Line 2: double sq = Math.sqrt(25); Line 3: int abs = Math.abs(-10); Line 4: double rand = Math.random();

Which line will cause a compile-time error?

Answer: (A) Line 1

The Math class has a private constructor, so you cannot create Math objects.

Line 1: new Math() causes a compile error. All Math methods are static, so you call them on the class itself (e.g., Math.sqrt()), not on an object.

Lines 2-4: All valid. Math.sqrt(25) returns 5.0. Math.abs(-10) returns 10. Math.random() returns a value in [0.0, 1.0).

Why Not the Others?

(B) Math.sqrt(25) returns double and is stored in a double. Perfectly valid.

(C) Math.abs(-10) with an int argument returns int. Stored in an int. Valid.

(D) Math.random() returns double and is stored in a double. Valid.

Common Mistake

The Math class is a utility class with only static methods. You never need (and cannot) create a Math object. Always call methods as Math.methodName().

AP Exam Tip

If a class has only static methods, you call them using the class name, not an object. Math.random(), not m.random(). The AP exam tests whether you know when to use new and when to call static methods directly.

Review this topic: Section 1.13 — The Math Class • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.