Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Compound Assignment Operators

Lesson ~10 min read 8 MCQs

In simple terms: 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.

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;

Comparing the verbose way to update a score versus the concise compound assignment.

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];
This diagram is a flowchart that shows how a variable's value changes through a series of compound assignment operations. It starts with a variable `x` equal to 10, then shows the result after applying `+= 5`, `*= 2`, and `--` in sequence. The final value of x is 29.

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:

  1. Take the value on the right (2).
  2. Add it to the current value of the variable on the left (score).
  3. 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
Tracing health points update using compound assignment.
```
  • Calculating a Sale
    An 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 Division
    Remember 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 Operator
    The 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.
Correct placement of the variable in compound assignment.

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

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    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.

    Example 1

    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:

    1. int numBoxes = 20;

      • What
        We declare an integer variable numBoxes and initialize it to 20.
      • Why
        This is our starting point. numBoxes is 20.
    2. numBoxes -= 8;

      • What
        This is shorthand for numBoxes = numBoxes - 8;. We calculate 20 - 8, which is 12.
      • Why
        We update numBoxes with this new result. numBoxes is now 12.
    3. numBoxes /= 2;

      • What
        This is shorthand for numBoxes = numBoxes / 2;. We calculate 12 / 2, which is 6.
      • Why
        The variable is updated again. numBoxes is now 6.
    4. numBoxes++;

      • What
        This is the post-increment operator. It's shorthand for numBoxes = numBoxes + 1;. We calculate 6 + 1, which is 7.
      • Why
        This is the final operation. The final value stored in numBoxes is 7.
    Example 2

    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:

    1. double itemCost = 50.0;

      • What: We initialize our double variable. itemCost is 50.0.
    2. itemCost /= 2.0;

      • What
        This is shorthand for itemCost = itemCost / 2.0;. A 50% discount is the same as dividing the price by 2. We calculate 50.0 / 2.0, which is 25.0.
      • Why
        We apply the discount. itemCost is now 25.0. Notice I used 2.0 instead of 2—it's good practice to keep your types consistent when working with doubles.
    3. itemCost += 5.0;

      • What
        This is shorthand for itemCost = itemCost + 5.0;. We calculate 25.0 + 5.0, which is 30.0.
      • Why
        We add the fee to the discounted price. The final value of itemCost is 30.0.

    This example shows that these operators work just as well with double values as they do with int values.

    Step-by-step trace of `numBoxes` through compound assignments.
    Avoiding the common mistake of using outdated variable 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.

    Tracing the T-shirt inventory problem with compound assignment operators.
    Tracing the score drill problem with increment/decrement and compound assignment.