Compound Assignment Operators

A Shortcut for "Update Using the Old Value"

x = x + 1; comes up so often that Java has a shortcut: x += 1;. Same idea works for every operator: += -= *= /= %=.

score += 10;   // same as: score = score + 10;
power *= 0.5;  // same as: power = power * 0.5;

Increment and Decrement

Adding or subtracting exactly 1 is common enough to get its own shortcut: ++ and --.

step++;   // same as step += 1, same as step = step + 1
timer--;

step++ (postfix) and ++step (prefix) both add 1 to step — the difference only shows up when the increment is used inside a larger expression on the same line: postfix uses the old value first, then increments; prefix increments first, then uses the new value. Used on its own line, like every example here, they behave identically.

A Real Example: Ramping Up Power

Instead of jumping straight to full power, increase it gradually, a little bit each time. (The if below is a sneak peek — Ch.5 covers it properly; for now, just read it as "only run the next line when this is true.")

double power = 0.0;
double rampRate = 0.02; // add 2% each time this runs

power += rampRate;
if (power > targetPower) {
    power = targetPower; // stop it from going past the target
}

That if check matters — without it, power would just keep climbing past where you wanted it to stop.

Tracing Code by Hand

Tracing means walking through code line by line, by hand, updating each variable as you go — a genuinely useful way to find bugs when just reading the code isn't enough.

int step = 0;
int delta = 5;
int total = 1;

step++;              // step: 1
delta -= 3;          // delta: 2
total = step + delta; // total: 1 + 2 = 3
step = total * 2;    // step: 3 * 2 = 6
delta %= 2;          // delta: 2 % 2 = 0
total--;             // total: 2

Final values: step = 6, delta = 0, total = 2.

Common Pitfalls

  • Forgetting the clamp when ramping. power += rampRate with no limit check will just keep climbing past your target.
  • Skipping ahead while tracing. Go one line at a time, in order — skipping ahead is how you miss the actual bug.
  • Compound assignment hides a cast. x = x + 1; and x += 1; are usually described as identical, but they're not quite: int x = 5; x = x * 0.5; won't compile (the right side is a double), while x *= 0.5; compiles fine and silently truncates x down to 2 — the compound form has an invisible (int) cast built in.

Key Takeaways

  • += -= *= /= %= update a variable using its current value, then store the result back.
  • ++ and -- are shortcuts for adding or subtracting exactly 1.
  • Ramping a motor's power up gradually is a real use of +=, checked against a limit each time.
  • Tracing code by hand — one line, one value at a time — is a real debugging skill.

Derived from csawesome-2026: unit-1-using-objects-and-methods/1.06-compound-assignment-operators.md (CSA 1.6)