AP CSA Unit 1 Day 21: Math Abs Pow
Share
Math.abs() and Math.pow()
Section 1.13 — The Math Class
Key Concept
The null keyword in Java represents a reference that points to no object. Any reference variable can be assigned null, including String, array, and custom class references. Calling any method on a null reference causes a NullPointerException at runtime. The AP exam tests null handling in method calls and comparisons. To safely check for null, use == (not .equals()): if (str != null && str.length() > 0). The short-circuit behavior of && prevents the method call when the reference is null.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 16
Trace the Math methods:
b: Math.pow(2, 3) returns 8.0 (always returns double).
Math.abs(a): Math.abs(-8) returns 8.
(int) b: (int) 8.0 = 8.
c: 8 + 8 = 16. Since c is an int, it prints as 16.
Why Not the Others?
(A) 0 would only occur if Math.abs(-8) returned -8 and the addition canceled. Math.abs() always returns the positive value: Math.abs(-8) = 8.
(C) c is declared as int, so it prints without a decimal point. The cast (int) b converts 8.0 to 8 before the addition.
(D) The code compiles fine. Math.pow() returns double, but the explicit cast (int) b converts it to int for the addition. Without the cast, it would not compile since double + int produces double, which cannot be assigned to int without casting. But the cast is present, so it works.
Common Mistake
Math.pow() always returns a double, even when both arguments are integers. If you need an int result, you must cast: (int) Math.pow(2, 3). Forgetting this cast is a common compilation error.
AP Exam Tip
All Math class methods are static, so you call them as Math.abs(), not on an object. Math.pow() and Math.sqrt() always return double. Math.abs() returns the same type as its argument.