AP CSA Unit 1 Day 5: Compound Narrowing
Share
Compound Assignment with Narrowing
Section 1.4 — Compound Assignment Operators
Key Concept
Compound assignment operators include an implicit narrowing cast that regular assignment does not. The expression x += 0.5 compiles when x is an int because it is equivalent to x = (int)(x + 0.5), which truncates the result. Without the compound operator, x = x + 0.5 would cause a compile error because x + 0.5 produces a double that cannot be assigned to an int without an explicit cast. The AP exam uses this distinction to create questions where one version compiles and the other does not.
Consider the following code segment.
What is printed as a result of executing the code segment?
Answer: (B) 12
Compound assignment operators perform implicit narrowing:
x += 2.5 is equivalent to x = (int)(x + 2.5).
10 + 2.5 = 12.5, then cast to int gives 12.
Unlike x = x + 2.5, which would NOT compile (because double cannot be assigned to int without explicit cast), the += operator includes an implicit cast.
Why Not the Others?
(A) x is an int and cannot store 12.5. The implicit cast in += truncates the result to 12.
(C) Casting truncates, it does not round. (int) 12.5 is 12, not 13.
(D) This is the tricky part: x += 2.5 compiles because compound assignment operators include an implicit narrowing cast. However, x = x + 2.5 would NOT compile.
Common Mistake
This is a subtle Java rule: x += value is NOT exactly the same as x = x + value. The compound form includes an implicit cast to the type of x. This means x += 2.5 compiles but x = x + 2.5 does not.
AP Exam Tip
This is an advanced AP exam concept. Compound assignment operators (+=, -=, *=, /=) include an implicit narrowing cast. If you see int += double, it compiles and truncates the result.