AP CSA Unit 1 Day 1: Tricky Casting

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

Tricky Casting in Expressions

Section 1.5 — Casting and Ranges

Key Concept

Casting placement in expressions determines when type conversion occurs relative to arithmetic operations. The expression (double)(a / b) performs integer division first, then casts the truncated result to double. In contrast, (double) a / b promotes a to double before division, preserving the decimal. On the AP exam, casting questions often combine multiple operations where the cast position changes the answer entirely. Always evaluate the cast at its exact position in the expression, not before or after.

Consider the following code segment.

double a = (int) 4.5 + (int) 3.9; double b = (int) (4.5 + 3.9); System.out.println(a + " " + b);

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

Answer: (A) 7.0 8.0

Cast placement changes everything:

a: (int) 4.5 = 4. (int) 3.9 = 3. Then 4 + 3 = 7, stored as 7.0 in a double.

b: 4.5 + 3.9 = 8.4 first (parentheses). Then (int) 8.4 = 8, stored as 8.0.

Casting each value individually truncates twice (losing 0.5 and 0.9 separately), while casting the sum truncates only once (losing just 0.4).

Why Not the Others?

(B) The first expression casts each value before adding. (int) 4.5 = 4 and (int) 3.9 = 3, so the sum is 7, not 8.

(C) The second expression adds first: 4.5 + 3.9 = 8.4, then casts to 8. Parentheses force addition before truncation.

(D) Both values are reversed from the correct answer. Casting individually gives 7; casting the sum gives 8.

Common Mistake

Truncation is not distributive: (int)(a + b) does not equal (int)a + (int)b. The lost decimals can add up when casting individually, changing the result.

AP Exam Tip

When you see multiple casts in an expression, carefully determine what each cast applies to. Draw parentheses around the exact operand being cast. This is a high-frequency AP exam trick.

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.