AP CSA Unit 1 Day 16: Casting Precision Loss

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

Casting Precision Loss

Section 1.5 — Casting and Ranges

Key Concept

Precision loss during casting is a subtle concept the AP exam tests in unexpected ways. Casting a double to an int always truncates toward zero: (int) 2.9 becomes 2, and (int) -2.9 becomes -2. But precision loss also occurs when converting large int values to float (not on the AP exam) or when integer division discards remainders. The exam combines casting with arithmetic to create multi-step precision loss: (int)(7.0 / 2) + (int)(7 / 2.0) requires evaluating each cast separately.

Consider the following code segment.

double price = 19.99; int cents = (int)(price * 100); int dollars = cents / 100; int leftover = cents % 100; System.out.println("$" + dollars + "." + leftover);

What is printed as a result of executing the code segment?

Answer: (A) $19.99

Trace the money conversion:

price * 100: 19.99 * 100 = 1999.0.

cents: (int) 1999.0 = 1999.

dollars: 1999 / 100 = 19.

leftover: 1999 % 100 = 99.

Output: "$" + 19 + "." + 99 = "$19.99".

Note: In some cases, floating-point imprecision could make 19.99 * 100 evaluate to 1998.9999..., which would cast to 1998 and produce $19.98. This is a real-world concern but the AP exam typically assumes exact arithmetic for simple cases like this.

Why Not the Others?

(B) This could happen due to floating-point imprecision in real Java, but the AP exam assumes clean arithmetic for simple decimal values.

(C) This would require cents % 100 = 0, meaning the price had no cents. But 1999 % 100 = 99.

(D) This would require cents / 100 = 20, meaning cents was at least 2000. But 1999 / 100 = 19.

Common Mistake

The division/modulo pair extracts dollars and cents: / 100 gives whole dollars, % 100 gives remaining cents. This is the same quotient/remainder pattern used for time conversion, but applied to money.

AP Exam Tip

The quotient-remainder pattern works for any base conversion: time (base 60), money (base 100), digit extraction (base 10). Recognize the pattern: / base gives the higher unit, % base gives the lower unit.

Review this topic: Section 1.5 — Casting and Ranges • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

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