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.
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.
| Operator | Example | Equivalent to | If 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.
| Statement | n |
|---|---|
| int n = 10; | 10 |
| n += 6; | 16 |
| n -= 4; | 12 |
| n *= 3; | 36 |
| n /= 5; | 7 |
| n %= 4; | 3 |
A Sequence of Compound Assignments
Trace n through each statement and predict the output.
int n = 10;
n += 6;
n -= 4;
n *= 3;
n /= 5;
n %= 4;
System.out.println(n);
3
- 1
n += 6. 10 + 6 = 16. - 2
n -= 4. 16 − 4 = 12. - 3
n *= 3. 12 × 3 = 36. - 4
n /= 5. Integer division: 36 ÷ 5 = 7. - 5
n %= 4. 7 % 4 = 3.
/= on an int is still integer division.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.
double cost = 200.0;
cost *= 1.5;
System.out.println(cost);
cost -= 30;
System.out.println(cost);
cost /= 4;
System.out.println(cost);
300.0
270.0
67.5
- 1
cost *= 1.5. 200.0 × 1.5 = 300.0. - 2
cost -= 30. Theint30 is widened to 30.0: 270.0. - 3
cost /= 4. Becausecostis adouble, this is real division: 67.5, not 67. - 4Type follows the variable. The same
/=that truncated with anintkeeps the fraction with adouble.
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.
The Right Side Is Grouped First
With x = 4 and y = 2, predict the results of the two statements.
int x = 4;
int y = 2;
x *= y + 1;
System.out.println(x);
int z = 4;
z = z * y + 1;
System.out.println(z);
12
9
- 1
x *= y + 1. Meansx = x * (y + 1): 4 × 3 = 12. - 2
z = z * y + 1. Ordinary precedence: 4 × 2 + 1 = 9. - 3Takeaway. When expanding a compound assignment into long form, put parentheses around the original right side, as in Figure 3.
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.
Counting Up and Down
Predict the output.
int lives = 3;
int coins = 0;
coins++;
coins++;
lives--;
coins += 5;
System.out.println("Lives: " + lives + ", Coins: " + coins);
Lives: 2, Coins: 7
- 1
coins++twice. 0 → 1 → 2. - 2
lives--. 3 → 2. - 3
coins += 5. 2 → 7. - 4Standalone statements. Each
++and--appears as its own statement, which is the clearest way to use them.
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.
| Pattern | Code | Use |
|---|---|---|
| Counter | count = 0; … count++; | How many times something happened |
| Accumulator | total = 0; … total += amount; | A running sum |
| Countdown | remaining--; | Items or turns left |
| Scaling | size *= 2; | Doubling, growth, interest |
| Unit peeling | n %= 60; | Keep what is left after removing whole units |
Building a Running Total
A fitness app records three workouts of 12, 8, and 15 minutes. Track the total and the count.
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);
35 minutes in 3 workouts
Average: 11.666666666666666
- 1Initialize first. Both the accumulator and the counter start at 0.
- 2Update for each item. Add the minutes with
+=and count the workout with++. - 3Use both for an average. Casting the total to
doublebefore dividing gives 35 ÷ 3 ≈ 11.67 minutes.
Splitting Seconds With /= and %=
Convert 7,385 seconds into hours, minutes, and seconds using compound operators.
int seconds = 7385;
int hours = seconds / 3600;
seconds %= 3600;
int minutes = seconds / 60;
seconds %= 60;
System.out.println(hours + "h " + minutes + "m " + seconds + "s");
2h 3m 5s
- 1Hours. 7385 ÷ 3600 = 2 (integer division).
- 2Keep the remainder.
seconds %= 3600leaves 7385 − 7200 = 185 seconds. - 3Minutes. 185 ÷ 60 = 3, and
seconds %= 60leaves 5. - 4Check. 2 × 3600 + 3 × 60 + 5 = 7385.
2h 3m 5s. %= replaces a variable with its remainder, which peels off one unit size at a time.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.
Updates That Do Not Do What They Seem
Each segment contains a mistake. Find it.
int score = 50;
score + 10;
int total;
total += 5;
int bonus = 7;
int points = 20;
points =+ bonus;
System.out.println(points);
7
- 1Segment A.
score + 10computes a value but stores it nowhere, so it is not a statement. Writescore += 10;. - 2Segment B.
total += 5must readtotalfirst, buttotalhas no value. Initialize it:int total = 0;. - 3Segment C.
=+is not an operator; Java reads it aspoints = +bonus;, an ordinary assignment of positive 7. It compiles but replaces 20 with 7 instead of adding. Write+=.
7 instead of 27. The symbol order matters: the arithmetic operator comes before the equals sign.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.
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.
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.