AP Computer Science A · Study guide

Compound Assignment Operators

AP® Computer Science A · Using Objects and Methods

Compound Assignment Operators

The shorthand operators +=, -=, *=, /=, and %=, the post-increment and post-decrement operators, and the counting and accumulating patterns they make easy to write.

Big Picture

Programs constantly update variables based on their current values: add points to a score, subtract a life, double a size, keep only a remainder. Compound assignment operators +=, -=, *=, /=, and %= can be used in place of the assignment operator for these updates. Each performs the indicated arithmetic between the value on the left and the value on the right and then assigns the result to the variable on the left. The post-increment operator ++ and post-decrement operator -- add 1 or subtract 1 from a numeric variable's stored value.

1Shorthand for Updating a Variable

Updating a variable with an ordinary assignment means writing its name twice: score = score + 10;. Compound assignment operators express the same update more compactly: score += 10;. The shorthand is easier to read, harder to mistype (there is only one copy of the variable name to get right), and immediately signals that the variable is being changed relative to its current value.

There is a compound operator for each arithmetic operator: += adds, -= subtracts, *= multiplies, /= divides, and %= replaces the variable with a remainder. They work with int and double variables, following the same type rules as the operators they abbreviate. In particular, /= on an int variable performs integer division.

Compound operators shine when the variable name is long or the update happens often. Compare weeklyStepTotal = weeklyStepTotal + todaySteps; with weeklyStepTotal += todaySteps;. The second line says the same thing with half the room for a typo, and a reader sees at a glance that the total is growing by today's steps. Most experienced programmers use the compound form whenever a variable is updated from its own value.

Figure 1. Each compound assignment operator performs an arithmetic operation between the variable and the value on the right, then stores the result back in the variable. The post-increment and post-decrement operators add or subtract exactly 1.
OperatorExampleEquivalent toIf x was 20
+=x += 4;x = x + 4;24
-=x -= 4;x = x - 4;16
*=x *= 4;x = x * 4;80
/=x /= 6;x = x / 6;3 (integer division)
%=x %= 6;x = x % 6;2
++x++;x = x + 1;21
--x--;x = x - 1;19

2How a Compound Assignment Works

A compound assignment operator performs the indicated arithmetic operation between the value on the left and the value on the right, and then assigns the result to the variable on the left. In three steps: read the variable's current value, combine it with the value on the right, and store the result back in the variable. It is exactly the same as the long form, which is why tracing compound assignments uses the same trace tables as ordinary assignments.

Because the variable is read before it is written, it must already have a value. total += 5; on a variable that was declared but never initialized is a compile-time error, the same as total = total + 5; would be.

Figure 2. A compound assignment reads the variable's current value, combines it with the value on the right, and stores the result back in the same variable.
Statementn
int n = 10;10
n += 6;16
n -= 4;12
n *= 3;36
n /= 5;7
n %= 4;3
Worked Example 1 Tracing

A Sequence of Compound Assignments

Trace n through each statement and predict the output.

Code
int n = 10;
n += 6;
n -= 4;
n *= 3;
n /= 5;
n %= 4;
System.out.println(n);
Output
3
  1. 1n += 6. 10 + 6 = 16.
  2. 2n -= 4. 16 − 4 = 12.
  3. 3n *= 3. 12 × 3 = 36.
  4. 4n /= 5. Integer division: 36 ÷ 5 = 7.
  5. 5n %= 4. 7 % 4 = 3.
Result: The final value is 3. Each compound operator updates the variable using its current value, and /= on an int is still integer division.
Worked Example 2 double variables

Compound Operators With Real Numbers

A store marks up a wholesale price by 50 percent, subtracts a 30-dollar coupon, then splits the cost among 4 friends. Predict each value.

Code
double cost = 200.0;
cost *= 1.5;
System.out.println(cost);
cost -= 30;
System.out.println(cost);
cost /= 4;
System.out.println(cost);
Output
300.0
270.0
67.5
  1. 1cost *= 1.5. 200.0 × 1.5 = 300.0.
  2. 2cost -= 30. The int 30 is widened to 30.0: 270.0.
  3. 3cost /= 4. Because cost is a double, this is real division: 67.5, not 67.
  4. 4Type follows the variable. The same /= that truncated with an int keeps the fraction with a double.
Result: The values are 300.0, 270.0, and 67.5. Compound operators work on double variables with ordinary real-number arithmetic.

3The Whole Right Side Comes First

When the right side is more than a single value, it is evaluated completely before being combined with the variable. x *= y + 1; means x = x * (y + 1);, not x = x * y + 1;. The right side behaves as though it were wrapped in parentheses.

This rule makes compound assignments predictable: compute the value on the right with normal precedence, then apply the operator. Whenever you rewrite a compound assignment in long form, for example while tracing, always put parentheses around the original right side.

Figure 3. In a compound assignment, the entire expression on the right is evaluated first, as if it were in parentheses, and only then combined with the variable.
Worked Example 3 Precedence

The Right Side Is Grouped First

With x = 4 and y = 2, predict the results of the two statements.

Code
int x = 4;
int y = 2;
x *= y + 1;
System.out.println(x);
int z = 4;
z = z * y + 1;
System.out.println(z);
Output
12
9
  1. 1x *= y + 1. Means x = x * (y + 1): 4 × 3 = 12.
  2. 2z = z * y + 1. Ordinary precedence: 4 × 2 + 1 = 9.
  3. 3Takeaway. When expanding a compound assignment into long form, put parentheses around the original right side, as in Figure 3.
Result: The results are 12 and 9. A compound assignment treats its entire right side as one value.
Common Mistake 1 · Expanding Without Parentheses

total -= cost + tax; subtracts the sum of cost and tax: it means total = total - (cost + tax);. Expanding it as total = total - cost + tax; would subtract the cost but add the tax.

4The Increment and Decrement Operators

The post-increment operator ++ and the post-decrement operator -- are used to add 1 or subtract 1 from the stored value of a numeric variable. The new value is assigned to the variable. count++; does the same thing as count += 1; and count = count + 1;.

Write ++ and -- after the variable name and use them as standalone statements, such as lives--; or as the update step of a counting loop. Placing them inside a larger expression, or before the variable name, makes code harder to read and is avoided here. For changes other than exactly 1, use += or -=.

Increment and decrement operators work on double variables too (temperature++ adds 1.0), but they are used overwhelmingly with int counters, indexes, and step numbers. Their most common home is the update step of a counting loop, where a variable such as i moves through 0, 1, 2, and so on, one step per repetition. Reading i++ as "move to the next one" makes such code easy to follow.

A good test of whether to use ++ is to ask whether the change is conceptually "one more" or "one fewer." A count of students who passed grows by one per student; a number of remaining tickets shrinks by one per sale. If the amount could ever be something other than 1, += with a named variable is clearer and easier to change later.

Worked Example 4 Increment and decrement

Counting Up and Down

Predict the output.

Code
int lives = 3;
int coins = 0;
coins++;
coins++;
lives--;
coins += 5;
System.out.println("Lives: " + lives + ", Coins: " + coins);
Output
Lives: 2, Coins: 7
  1. 1coins++ twice. 0 → 1 → 2.
  2. 2lives--. 3 → 2.
  3. 3coins += 5. 2 → 7.
  4. 4Standalone statements. Each ++ and -- appears as its own statement, which is the clearest way to use them.
Result: The output is Lives: 2, Coins: 7. Use ++ and -- for changes of exactly 1 and += for any other amount.

5Counting and Accumulating

Two patterns appear in nearly every program that processes data. A counter starts at 0 and increases by 1 each time an event happens: each time a student passes, each time a word is found. An accumulator starts at 0 and adds each new value: a running total of minutes, points, or prices. Counters use ++; accumulators use +=. Together they produce averages, totals, and percentages.

The starting value matters. A total that starts at anything other than 0 is wrong from the beginning, and a product that is built with *= must start at 1, since starting at 0 would make every product 0. Right now the updates are written out one by one; once loops are available, the same single update statement will run once per item, which is where these patterns become truly powerful.

Figure 4. Counters and accumulators are two of the most common uses of compound assignment. Both must start at a sensible initial value, usually 0.
PatternCodeUse
Countercount = 0; … count++;How many times something happened
Accumulatortotal = 0; … total += amount;A running sum
Countdownremaining--;Items or turns left
Scalingsize *= 2;Doubling, growth, interest
Unit peelingn %= 60;Keep what is left after removing whole units
Worked Example 5 Accumulating

Building a Running Total

A fitness app records three workouts of 12, 8, and 15 minutes. Track the total and the count.

Code
int totalMinutes = 0;
int workouts = 0;
totalMinutes += 12;
workouts++;
totalMinutes += 8;
workouts++;
totalMinutes += 15;
workouts++;
System.out.println(totalMinutes + " minutes in " + workouts + " workouts");
System.out.println("Average: " + (double) totalMinutes / workouts);
Output
35 minutes in 3 workouts
Average: 11.666666666666666
  1. 1Initialize first. Both the accumulator and the counter start at 0.
  2. 2Update for each item. Add the minutes with += and count the workout with ++.
  3. 3Use both for an average. Casting the total to double before dividing gives 35 ÷ 3 ≈ 11.67 minutes.
Result: The total is 35 minutes over 3 workouts, an average of about 11.67. This accumulate-and-count pattern returns constantly once loops can repeat the updates automatically.
Worked Example 6 Division and remainder

Splitting Seconds With /= and %=

Convert 7,385 seconds into hours, minutes, and seconds using compound operators.

Code
int seconds = 7385;
int hours = seconds / 3600;
seconds %= 3600;
int minutes = seconds / 60;
seconds %= 60;
System.out.println(hours + "h " + minutes + "m " + seconds + "s");
Output
2h 3m 5s
  1. 1Hours. 7385 ÷ 3600 = 2 (integer division).
  2. 2Keep the remainder. seconds %= 3600 leaves 7385 − 7200 = 185 seconds.
  3. 3Minutes. 185 ÷ 60 = 3, and seconds %= 60 leaves 5.
  4. 4Check. 2 × 3600 + 3 × 60 + 5 = 7385.
Result: 7,385 seconds is 2h 3m 5s. %= replaces a variable with its remainder, which peels off one unit size at a time.
Common Mistake 2 · Starting an Accumulator at the Wrong Value

A sum must start at 0 and a product at 1. Starting a product at 0 makes every result 0; starting a sum at the first value and then also adding that value counts it twice. Decide what the "empty" result should be and initialize to it.

6Common Mistakes With Updates

Most compound-assignment mistakes fall into three groups. The first is computing a value without storing it, as in score + 10;, which the compiler rejects because it does nothing. The second is updating a variable that was never initialized. The third is reversing the symbols: =+ instead of +=. Java reads x =+ 5; as x = +5;, an ordinary assignment, so the code compiles and silently replaces the value instead of adding to it.

When an update seems to have no effect, or a total comes out equal to the last value added, check the operator character by character. The arithmetic symbol always comes first, immediately followed by the equals sign, with no space between them.

Worked Example 7 Common errors

Updates That Do Not Do What They Seem

Each segment contains a mistake. Find it.

Segment A
int score = 50;
score + 10;
Segment B
int total;
total += 5;
Segment C
int bonus = 7;
int points = 20;
points =+ bonus;
System.out.println(points);
Output
7
  1. 1Segment A. score + 10 computes a value but stores it nowhere, so it is not a statement. Write score += 10;.
  2. 2Segment B. total += 5 must read total first, but total has no value. Initialize it: int total = 0;.
  3. 3Segment C. =+ is not an operator; Java reads it as points = +bonus;, an ordinary assignment of positive 7. It compiles but replaces 20 with 7 instead of adding. Write +=.
Result: A does not compile, B does not compile, and C silently prints 7 instead of 27. The symbol order matters: the arithmetic operator comes before the equals sign.
Common Mistake 3 · Writing =+ Instead of +=

total =+ price; compiles, but it assigns +price to total, discarding the old total. The same happens with =-, which assigns the negative of the value. If a running total keeps showing only the latest amount, look for a reversed operator.

Common Mistake 4 · Forgetting That /= Uses Integer Division

If count is an int holding 7, count /= 2; stores 3, not 3.5. Compound operators follow the same type rules as the operators they abbreviate.

Four Habits for Compound Assignment

1. Read It as Read-Combine-Store

x op= v uses x's current value, then replaces it.

2. Parenthesize the Right Side

x *= a + b means x = x * (a + b).

3. Initialize Before Updating

Sums start at 0, products at 1, counters at 0.

4. ++ and -- Stand Alone

Use them as their own statements for changes of exactly 1.

Core Synthesis

Compound assignment operators +=, -=, *=, /=, and %= can be used in place of the assignment operator in numeric expressions. A compound assignment operator performs the indicated arithmetic operation between the value on the left and the value on the right and then assigns the result to the variable on the left, with the entire right side evaluated first. The post-increment operator ++ and post-decrement operator -- add 1 or subtract 1 from the stored value of a numeric variable, and the new value is assigned to the variable. These operators power the counting and accumulating patterns used throughout programming.