In AP Computer Science A, compound assignment operators are shorthand ways to update the value of a variable. They let you do math on a variable and then store the result back into the same variable in one step.
Normally, if you want to add 5 to a variable x, you might write:
x = x + 5;
With a compound assignment operator, you can write the same idea as:
x += 5;
This means: take the current value of x, add 5, and store it back into x.
| Operator | Example | Equivalent To | Meaning |
|---|---|---|---|
| += | x += 3; | x = x + 3; | Add and assign |
| -= | x -= 2; | x = x - 2; | Subtract and assign |
| *= | x *= 4; | x = x * 4; | Multiply and assign |
| /= | x /= 2; | x = x / 2; | Divide and assign |
| %= | x %= 10; | x = x % 10; | Take remainder and assign |
Example:
int total = 0;
total += 10; // total is now 10
total -= 3; // total is now 7
total *= 2; // total is now 14
If a variable is an int, it still behaves like an integer even when you use compound assignment. That means integer division cuts off the decimal.
int slices = 11;
slices /= 2; // slices becomes 5, NOT 5.5
Because slices is an int, it cannot keep the .5 part. The decimal is thrown away.
Compound assignment can also force a value back into the original variable’s type.
int x = 5;
x *= 2.5; // Allowed. x becomes 12
Here’s what happened:
This silent cut-off (called truncation) is something the AP exam likes to test.
You need to be able to read and write statements like:
i += 2; // counting by 2
sum += value; // running total
count %= 10; // keep last digit only
The College Board expects you to know what the operators +=, -=, *=, /=, and %= do and be able to predict the new value of the variable after they run.