AP CSA Unit 1 Day 6: Compound Assignment

Unit 1 Foundation (Cycle 1) Day 6 of 28 Foundation

Compound Assignment Operators

Section 1.4 — Compound Assignment Operators

Key Concept

Casting in Java allows you to explicitly convert between types. Narrowing casts like (int) 3.7 always truncate toward zero, producing 3 — Java never rounds during a cast. Widening conversions from int to double happen automatically. A frequent AP exam mistake involves the order of operations with casting: (double)(7 / 2) gives 3.0 because the integer division happens first, while (double) 7 / 2 gives 3.5 because the cast applies to 7 before the division.

Consider the following code segment.

int x = 20; x /= 3; x += 4; x *= 2; System.out.println(x);

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

Answer: (A) 20

Expand each compound operator and trace:

Start: x = 20

x /= 3: x = 20 / 3 = 6 (integer division truncates)

x += 4: x = 6 + 4 = 10

x *= 2: x = 10 * 2 = 20

Output: 20

Why Not the Others?

(B) This might come from computing 20 / 3 = 6, then 6 + 4 = 10, but miscalculating the final step. 10 * 2 = 20, not 18.

(C) 14 would result from skipping the /= 3 step: 20 + 4 = 24, then 24 / 2 = 12... but that does not match either. This value does not follow any correct trace path.

(D) This likely comes from rounding 20 / 3 to 7 instead of truncating to 6. Integer division always truncates toward zero, never rounds.

Common Mistake

Expand compound operators first: x /= 3 means x = x / 3. The integer division on the first step is the critical trap: 20 / 3 = 6, not 6.67 or 7.

AP Exam Tip

For compound assignment questions, rewrite each line as a full expression: x += 4 becomes x = x + 4. Then trace step by step, updating the value of x after each line.

Review this topic: Section 1.4 — Compound Assignment Operators • Unit 1 Study Guide

More Practice

Back to blog

Leave a comment

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