AP CSA Unit 1 Day 23: Math Sqrt Casting
Share
Math.sqrt() and Casting Results
Section 1.13 — The Math Class
Key Concept
Method tracing requires you to track the state of all variables through each line of execution. When a method is called, a new stack frame is created with the parameter values. Changes to local variables inside a method do not affect variables in the calling method. For object references, changes to the object's fields persist because both the caller and method share the same object. The AP exam frequently presents multi-method traces where the output depends on the order of method calls and which values are returned versus discarded.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (A) 7 49 false
Trace through:
Math.sqrt(50): Returns approximately 7.071... (a double).
(int) 7.071: Casting truncates to 7.
square: 7 * 7 = 49.
square == n: 49 == 50 is false.
Output: 7 49 false
Why Not the Others?
(B) 49 does not equal 50, so the comparison is false. Casting the square root to int loses precision, so squaring the truncated root does not recover the original value.
(C) root is declared as int, so it stores 7, not 7.07. The decimal is lost when casting.
(D) Casting 7.071 to int gives 7, not 8. Casting always truncates toward zero, never rounds up.
Common Mistake
Casting a double to int always truncates. (int) 7.071 is 7, not 8. This means the squared result (49) will not equal the original value (50) for non-perfect squares.
AP Exam Tip
Be careful with Math.sqrt(): it returns a double. If you cast it to int and then square it, you only get the original value back if the original was a perfect square. This is a useful pattern for testing perfect squares.