Skip to the content.

Compound Assignment Operators

Compound Assignment Operators (AP CS A, Unit 1.6)

What Are They, and What Do They Help With?

A compound assignment operator combines an arithmetic (or other) operation with an assignment in one statement.

For example, instead of writing:

score = score + 10;

You can write:

score += 10;

Learning Goals For End of Lesson

By the end of this lesson, you’ll be able to:

  • Transform clunky x = x + y statements into sleek compound assignments
  • Master all the essential operators (+=, -=, *=, /=, %=, ++, --)
  • Understand evaluation order and avoid common traps

Table of Different Operations in Java

Operator Equivalent Full Form Purpose / Typical Use
+= x = x + y Add to a running total; accumulate; string concatenation when LHS is a String.
-= x = x - y Subtract / reduce something (e.g. subtract a cost, penalty).
*= x = x * y Multiply — useful for scaling, growth, repeated doubling or factors.
/= x = x / y Divide — scaling down; used in averages, proportions. (Watch out: integer division if both operands are ints.)
%= x = x % y Remainder after division — wrap-around logic, parity checks, keeping things within bounds.
++ x = x + 1 Add one; often used in loops, counters.
-- x = x - 1 Subtract one; used in loops as well as decrementing counters.

Popcorn Hack #1:

Transform this beginner code into more advanced code using compound assignment operators.

int playerScore = 1000;
int playerHealth = 100;
int enemiesDefeated = 0;

// Player defeats an enemy worth 250 points
// playerScore = playerScore + 250;
playerScore += 250;
// Player takes 15 damage
// playerHealth = playerHealth - 15;
playerHealth -= 15;

// Enemy count goes up
// enemiesDefeated = enemiesDefeated + 1;
enemiesDefeated += 1;

// Boss battle: double the current score!
// playerScore = playerScore * 2;
playerScore *= 2;

// Healing potion restores health to 80% of current
// playerHealth = playerHealth * 4;
playerHealth *= 4;
// playerHealth = playerHealth / 5;  // 4/5 = 0.8, but we need integer math
playerHealth /= 5;

Examples to further understand this concept:

public class Example {
  public static void main(String[] args) {
    int score = 100;
    double average = 85.5;
    score += 50;       // score = 150
    score -= 25;       // score = 125
    score *= 2;        // score = 250
    score /= 5;        // score = 50  (integer division)
    score %= 15;       // score = 5   (50 % 15)
    average += 4.5;    // average = 90.0
    int count = 0;
    count++;           // count = 1
    count--;
    System.out.println(count); // count = 0
  }
}
Example.main(null);

// Output: 0
// Output: 0 
// Explanation: The code demonstrates various assignment and arithmetic operations, including integer division and the modulus operator. The final output is 0 after incrementing and decrementing the count variable.
0

Popcorn Hack #2:

Write a short program where a variable called score starts at 100. Use at least three different compound assignment operators to update score, and print the result after each step.

Example goals to try:

  1. Deduct points for a wrong answer (-=)
  2. Double the score with a power-up (*=)
  3. Find remainder after dividing by 7 (%=)
public class AnvayVaheehee {
    public static void main(String[] args) {
        int score = 100;
        System.out.println("Starting score: " + score);

        score -= 15;
        System.out.println("After wrong answer (-=): " + score);

        score *= 2;
        System.out.println("After power-up (*=): " + score);

        score %= 7;
        System.out.println("After remainder (%=): " + score);
    }
}

AnvayVaheehee.main(null);

Starting score: 100
After wrong answer (-=): 85
After power-up (*=): 170
After remainder (%=): 2

Important Rules to keep in mind (AP Test-Specific):

  1. You can only use these when the variable on the left already exists and has a value.

  2. Integer division: when you divide two ints, the fractional part is truncated. Be careful with /=.

  3. Only post-form (x++, x--) is in scope for the AP exam. Prefix forms (++x) are out of scope.

Homework Assignment for Unit 1.6

Due: 10/9/2025


Assignment Overview

Now that you’ve learned about compound assignment operators, it’s time to put them into practice! You’ll create a short Java program that models a real-world scenario.

Requirements

Your program must include:

  • At least 3 different compound assignment operators (+=, -=, *=, /=, %=, ++, --)
  • Meaningful variable names that make sense for your chosen scenario
  • Print statements showing the value after each operation
  • Comments explaining what each operation represents in your scenario
  • A main method that runs your simulation

Scenario Options

Choose ONE of the following scenarios to model:

Option A: Social Media Influencer Simulator

Model the journey of a content creator tracking their growth:

Suggested variables to track:
  • followers - Start with some initial followers
  • posts - Number of posts made
  • engagement - Likes/comments received
  • sponsorshipEarnings - Money earned from sponsors
Example operations you might use:
  • Gain followers from a viral post (followers += 1000)
  • Lose followers from controversial content (followers -= 50)
  • Double engagement from a trending hashtag (engagement *= 2)
  • Calculate average engagement per post (engagement /= posts)
  • Find your ranking position (position %= 100)

Option B: Bank Account Manager

Simulate managing a personal bank account over time:

Suggested variables to track:
  • balance - Current account balance
  • transactions - Number of transactions made
  • monthlyFee - Account maintenance costs
  • interestRate - Interest earned/applied
Example operations you might use:
  • Add monthly salary (balance += 3000)
  • Subtract rent payment (balance -= 1200)
  • Apply interest rate (balance *= 1.02)
  • Average monthly spending (spending /= 12)
  • Check account tier eligibility (tier %= 5)

Option C: Fitness Progress Tracker

Track your fitness journey and daily health metrics:

Suggested variables to track:
  • totalCalories - Calories consumed/burned
  • workoutDays - Days you’ve exercised
  • stepCount - Daily step count
  • weightGoal - Target weight progress
Example operations you might use:
  • Add calories from meals (totalCalories += 600)
  • Burn calories from exercise (totalCalories -= 300)
  • Double steps from an active day (stepCount *= 2)
  • Calculate average daily steps (stepCount /= 7)
  • Track weekly goal progress (progress %= 7)

Sample Output Format

Your program should produce an output similar to this (this is an example for Option A but the format for other options is similar):

=== SOCIAL MEDIA SIMULATOR ===

Starting followers: 500

Posted a new video!

Followers: 750 (+250 from the viral video)

Controversial opinion posted...

Followers: 700 (-50 from upset followers)

Trending hashtag boost!

Followers: 1400 (doubled from trending!)

Average engagement per post: 35

Final ranking position: 400

=== SIMULATION COMPLETE ===

public class SocialMediaSimulator {
    public static void main(String[] args) {
        System.out.println("=== SOCIAL MEDIA INFLUENCER SIMULATOR ===\n");

        // Initial setup
        int followers = 500;         // Starting followers
        int posts = 5;               // Number of posts made
        int engagement = 300;        // Total likes/comments
        double sponsorshipEarnings = 200.0; // Starting sponsor money in dollars

        System.out.println("Starting followers: " + followers);
        System.out.println("Starting engagement: " + engagement);
        System.out.println("Starting sponsorship earnings: $" + sponsorshipEarnings + "\n");

        // 1. Gained followers from a viral post
        followers += 1000; // increase followers
        System.out.println("A video went viral!");
        System.out.println("Followers: " + followers + " (+1000 from the viral post)\n");

        // 2. Lost followers due to a controversy
        followers -= 200; // lose followers
        System.out.println("Posted a controversial opinion...");
        System.out.println("Followers: " + followers + " (-200 from upset followers)\n");

        // 3. Engagement doubles thanks to a trending hashtag
        engagement *= 2; // double engagement
        System.out.println("Trending hashtag boost!");
        System.out.println("Engagement: " + engagement + " (doubled from trending!)\n");

        // 4. Calculate average engagement per post
        engagement /= posts; // find average engagement per post
        System.out.println("Average engagement per post: " + engagement + "\n");

        // 5. Sponsorship earnings increase by 50%
        sponsorshipEarnings *= 1.5; // increase earnings
        System.out.println("Signed a new sponsor deal!");
        System.out.println("Sponsorship earnings: $" + sponsorshipEarnings + "\n");

        // 6. Determine ranking position in the top 1000 influencers
        int rankingPosition = 1234;
        rankingPosition %= 1000; // get remainder after dividing by 1000
        System.out.println("Final ranking position: " + rankingPosition + "\n");

        System.out.println("=== SIMULATION COMPLETE ===");
    }
}

SocialMediaSimulator.main(null);

=== SOCIAL MEDIA INFLUENCER SIMULATOR ===

Starting followers: 500
Starting engagement: 300
Starting sponsorship earnings: $200.0

A video went viral!
Followers: 1500 (+1000 from the viral post)

Posted a controversial opinion...
Followers: 1300 (-200 from upset followers)

Trending hashtag boost!
Engagement: 600 (doubled from trending!)

Average engagement per post: 120

Signed a new sponsor deal!
Sponsorship earnings: $300.0

Final ranking position: 234

=== SIMULATION COMPLETE ===

Submission Instructions

Create a section on your personal blog documenting one of the three provided options. After updating your blog, please submit a personal blog link of your completed assignment to the google form link inserted in the ‘CSA Sign Up Sheet - Team Teach - Trimester 1’ spreadsheet.

Here is where to submit your homework by 10/9/2025! (Lesson 1.6 Hacks + Homework Submission Form)

Please read the requirements in the form description before submitting your homework.