Compound Assignment Operators
Why this matters
Imagine you're building a simple scoreboard app for your school's basketball team in Dallas. You have a variable called score that starts at 0. When your team's star player, Priya, scores a two-point shot, you update the score. In code, that looks like this:
score = score + 2;
A few minutes later, she sinks a three-pointer:
score = score + 3;
This works perfectly, but notice the repetition? You're constantly writing score = score + .... Programmers are always looking for ways to write cleaner, more efficient code. What if there was a shorthand for "take a variable, do some math with it, and save the result right back into that same variable"?
That's exactly what this lesson is about. We'll learn the shortcuts that make your code more concise and professional.
Concept overview
flowchart TD
A[Start: int x = 10] --> B{x += 5};
B --> C[x is now 15];
C --> D{x *= 2};
D --> E[x is now 30];
E --> F{x--};
F --> G[x is now 29];
G --> H[End];
Core explanation
Let's get right to it. The code we saw in our basketball example, score = score + 2;, feels a little clunky. You have to type the variable name score twice. Java gives us a much cleaner way to do this.
Combining Math and Assignment
The line score = score + 2; can be rewritten using the addition assignment operator, +=:
score += 2;
These two lines do the exact same thing! The += operator tells Java:
- Take the value on the right (
2). - Add it to the current value of the variable on the left (
score). - Store the final result back into the variable on the left (
score).
Think of it like making a deposit at the bank. If you have $100 in your account and you deposit $20, you don't say "my new balance is my old balance of $100 plus $20." You just say you're adding $20. The += operator is that direct.
This pattern works for all the basic arithmetic operations:
| Operator | Example | Equivalent to... |
|---|---|---|
+= |
x += 5; |
x = x + 5; |
-= |
x -= 3; |
x = x - 3; |
*= |
x *= 2; |
x = x * 2; |
/= |
x /= 4; |
x = x / 4; |
%= |
x %= 3; |
x = x % 3; |
Let's see them in action with a few quick examples:
- Tracking Game Health: Your character in a video game, Marcus, has 100 health points. He takes 15 points of damage.
int health = 100; health -= 15; // health is now 85
```
- Calculating a SaleAn item's price is being doubled for a special promotion, then a coupon is applied.
double price = 25.50; price *= 2; // price is now 51.00 price -= 10; // price is now 41.00 - Integer DivisionRemember how integer division works in Java—it drops the decimal. This is a place students often get tripped up.
int totalCookies = 25; totalCookies /= 4; // 25 divided by 4 is 6.25. As an int, it's 6. // totalCookies is now 6. - Using the Modulo OperatorThe modulo operator (
%) gives you the remainder of a division. It's incredibly useful. Imagine you have 125 cents and you want to find out how many cents are left after you take out all the whole dollars.int cents = 125; cents %= 100; // 125 divided by 100 is 1 with a remainder of 25. // cents is now 25.
The Ultimate Shortcut: Increment and Decrement
The single most common operation in programming is adding or subtracting 1. You might be counting button clicks, loop iterations, or items in a shopping cart.
You could write:
count = count + 1;
Or, using our new operator:
count += 1;
But it's so common that Java has an even shorter way: the post-increment operator ++.
count++;
All three of these lines accomplish the exact same thing: they increase the value of count by 1. The ++ is just the fastest and most common way to write it.
Similarly, there's a post-decrement operator -- for subtracting 1.
lives--; // is the same as lives = lives - 1;
On the AP exam, you'll only see the post-increment (x++) and post-decrement (x--) versions. This means the ++ or -- comes after the variable. For now, when you see x++; or x--; on a line by itself, just think of it as a simple command: "add 1 to x" or "subtract 1 from x."
Using these operators makes your code cleaner, easier to read for other programmers, and shows you have a solid grasp of Java fundamentals.
See it in action
Worked examples
Let's walk through a few problems to make sure these concepts are crystal clear. I'll show you my thought process, step-by-step.
Tracking Inventory
Problem: A variable numBoxes starts at 20. Your code then runs the following lines. What is the final value of numBoxes?
int numBoxes = 20;
numBoxes -= 8;
numBoxes /= 2;
numBoxes++;
Solution Walkthrough:
-
int numBoxes = 20;- WhatWe declare an integer variable
numBoxesand initialize it to 20. - WhyThis is our starting point.
numBoxesis20.
- What
-
numBoxes -= 8;- WhatThis is shorthand for
numBoxes = numBoxes - 8;. We calculate20 - 8, which is12. - WhyWe update
numBoxeswith this new result.numBoxesis now12.
- What
-
numBoxes /= 2;- WhatThis is shorthand for
numBoxes = numBoxes / 2;. We calculate12 / 2, which is6. - WhyThe variable is updated again.
numBoxesis now6.
- What
-
numBoxes++;- WhatThis is the post-increment operator. It's shorthand for
numBoxes = numBoxes + 1;. We calculate6 + 1, which is7. - WhyThis is the final operation. The final value stored in
numBoxesis7.
- What
Calculating a Final Price
Problem: A double variable itemCost is initialized to 50.0. You're running a promotion in your Chicago store. The item gets a 50% discount, and then a $5 environmental fee is added. What is the final itemCost?
double itemCost = 50.0;
itemCost /= 2.0;
itemCost += 5.0;
Solution Walkthrough:
-
double itemCost = 50.0;- What: We initialize our
doublevariable.itemCostis50.0.
- What: We initialize our
-
itemCost /= 2.0;- WhatThis is shorthand for
itemCost = itemCost / 2.0;. A 50% discount is the same as dividing the price by 2. We calculate50.0 / 2.0, which is25.0. - WhyWe apply the discount.
itemCostis now25.0. Notice I used2.0instead of2—it's good practice to keep your types consistent when working with doubles.
- What
-
itemCost += 5.0;- WhatThis is shorthand for
itemCost = itemCost + 5.0;. We calculate25.0 + 5.0, which is30.0. - WhyWe add the fee to the discounted price. The final value of
itemCostis30.0.
- What
This example shows that these operators work just as well with double values as they do with int values.
Try it yourself
Ready to try a couple on your own? Think through the steps just like we did in the worked examples.
Problem 1: The T-Shirt Inventory
You're tracking inventory for an online store based in Seattle. You start with 50 T-shirts. A new shipment arrives, doubling your stock. Over the day, you sell 15 shirts. Finally, you want to see how many shirts will be left over if you package the rest into boxes that hold 4 shirts each.
Declare an int variable shirts and apply the operations. Then, use the modulo assignment operator (%=) to find the leftovers. What is the final value of shirts after all operations?
Hint: You'll need to use `=,-=, and finally%=`.*
Problem 2: Score Drill
A variable int score = 0; is put through the following sequence. Trace the value of score after each line. What is its final value?
score++;
score += 9;
score--;
score /= 4;
Hint: Remember that integer division drops the decimal.
Practice — 8 questions
In simple terms, compound assignment operators are shortcuts in code for doing math and updating a variable's value at the same time, like adding points to a score.
int numBoxes = 20;
numBoxes -= 8;
numBoxes /= 2;
numBoxes++;
- 1.6.A: Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.
- 1.6.A.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.
- 1.6.A.2
- The post-increment operator ++ and 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.
flowchart TD
A[Start: int x = 10] --> B{x += 5};
B --> C[x is now 15];
C --> D{x *= 2};
D --> E[x is now 30];
E --> F{x--};
F --> G[x is now 29];
G --> H[End];
Read what Saavi narrates
(gentle, warm intro music fades)
Hi everyone, it's Saavi from Shrutam. Let's talk about some really useful shortcuts in Java today.
Imagine you're coding a scoreboard for your school's basketball game. You have a variable for the score. Every time your team scores, you have to update it. You might write something like 'score equals score plus two'. It works, but it's a little repetitive. What if there was a faster way?
Well, there is! This lesson is all about learning the shorthand commands Java gives us to modify variables. We're going to look at special operators that combine a math operation and an assignment in one clean step.
Let's walk through an example together. Imagine we have a variable called `numBoxes`, and it starts with the value 20.
The first line of code we see is `numBoxes -= 8`. That little 'minus equals' operator is a shortcut for 'numBoxes equals numBoxes minus 8'. So, we take the current value, 20, subtract 8, and get 12. Great. The value of `numBoxes` is now 12.
The next line is `numBoxes /= 2`. This is the shortcut for division. We take our current value, 12, and divide it by 2. The result is 6. So, `numBoxes` is now 6.
Finally, we see `numBoxes++`. This is the super-shortcut for just adding one. So we take our current value, 6, and add 1. The final value is 7. See how we just walked through it, one step at a time, always using the most recent value?
A really common mistake I see is when students accidentally reverse the operator. They'll write 'equals plus' instead of 'plus equals'. If you write `x =+ 5`, the computer just sees it as `x = 5`, which completely overwrites the old value of x. That's not what you want! So remember, the math symbol always comes first: plus-equals, minus-equals, and so on.
These little shortcuts might seem small, but they make your code cleaner and more professional. Take your time, practice with them, and they'll become second nature. You've got this.
(gentle, warm outro music fades in)
The compiler reads `x =+ 5;` as `x = (+5);`, which simply assigns the value `5` to `x`, ignoring its previous value. It's a valid assignment, but it doesn't do what you intended.
Always write the math part of the operator first, then the equals sign: `+=`, `-=`, `*=`, etc.
The expression `x + 1` calculates a new value, but because you aren't assigning it to anything, that value is immediately discarded. The variable `x` remains unchanged.
To change the variable, you must use an assignment: `x = x + 1;`, `x += 1;`, or `x++;`.
The left side of an assignment operator must be a variable—a named location in memory where a result can be stored. You can't change the value of the number `100`.
Make sure the variable you intend to modify is on the left side: `balance -= cost;`.
If you have `int x = 11;` and you write `x /= 2;`, the result is `5`, not `5.5`. Java's integer division truncates (chops off) the decimal part.
Be mindful of your variable types. If you need decimal precision, use a `double`. If you are using `int`, expect the decimal to be dropped.
Students sometimes think `x %= 10;` is a way to get 10% of x. The `%` symbol is the *modulo* operator, which calculates the *remainder* of a division.
Remember that `x %= 10;` is shorthand for `x = x % 10;`. It answers the question, "After dividing x by 10, what is the integer remainder?"