1.06 Compound Assignment Operators
Use shorthand operators (+=, -=, etc.) and increment/decrement (++, --) to modify variables.
Reference Guide
Compound Assignment Operators
| Operator | Full Form | Use Case | Example |
|---|---|---|---|
+= |
x = x + y |
Add to total; accumulate values; string concatenation | score += 10 |
-= |
x = x - y |
Subtract/reduce; apply penalties; decrease counters | health -= 15 |
*= |
x = x * y |
Scale values; apply multipliers; repeated multiplication | price *= 1.15 (apply 15% increase) |
/= |
x = x / y |
Divide/scale down; compute averages; normalize values | average /= count |
%= |
x = x % y |
Remainder after division; wrap-around logic; parity checks | position %= 10 |
Increment and Decrement Operators
| Operator | Full Form | Behavior | AP Scope |
|---|---|---|---|
x++ |
x = x + 1 |
Post-increment: return old value, then increment | IN SCOPE |
x-- |
x = x - 1 |
Post-decrement: return old value, then decrement | IN SCOPE |
++x |
x = x + 1 |
Pre-increment: increment, then return new value | OUT OF SCOPE |
--x |
x = x - 1 |
Pre-decrement: decrement, then return new value | OUT OF SCOPE |
Key Point for AP: Post-form (x++, x–) returns the value before incrementing. This matters when used in expressions.
Operator Precedence (Review)
1. Parentheses ()
2. Increment/Decrement (++, --)
3. Multiplication, Division, Modulus (*, /, %)
4. Addition, Subtraction (+, -)
5. Assignment (=, +=, -=, *=, /=, %=)
College Board Requirements
Topic 1.6, Compound Assignment Operators, is required content tested on the AP Computer Science A Exam. The College Board’s official course framework defines the operators this lesson covers:
“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.” (College Board, 2025, p. 38)
It also explicitly scopes the increment/decrement operators taught in this lesson:
“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.” (College Board, 2025, p. 38)
This is the source of the Reference Guide’s note that only post-form operators are in scope for the AP Exam; the CED’s exclusion statement specifically places prefix forms like ++x outside the course.
Lesson Plan
Learning Objective: By the end of this lesson, you will be able to correctly apply all compound assignment operators, understand their equivalence to expanded forms, predict results of increment and decrement operations, and choose appropriate operators for different contexts.
Success Criteria: You can replace long-form expressions with appropriate compound operators, predict the output of expressions using increment and decrement operators, and explain why each operator is the right choice for a given situation.
Tech Talk & Introduction
A compound assignment operator combines an operation with assignment in one statement. Instead of writing the variable name twice, you write it once with the operator.
The Core Idea:
Long form: score = score + 10;
Compound: score += 10;
These are equivalent. The compound form is cleaner, but it is not just syntactic sugar - it represents a specific operation on a specific variable. Understanding this helps you write intentional code and predict results correctly.
Why do we do this? Compound operators make code more readable and less error-prone. They appear frequently in the AP exam. Understanding increment and decrement operators is essential for loops and counter patterns.
This example demonstrates the main compound operators:
// CODE_RUNNER: Compound Assignment Operators
// Run it, then change a value and predict the new output
public class CodeRunner1_CompoundOperators {
public static void main(String[] args) {
int score = 100;
score += 50; // score = 150 (add and assign)
score -= 25; // score = 125 (subtract and assign)
score *= 2; // score = 250 (multiply and assign)
score /= 5; // score = 50 (divide and assign)
score %= 15; // score = 5 (remainder and assign)
int count = 0;
count++; // count = 1 (increment by 1)
count--; // count = 0 (decrement by 1)
System.out.println("Final score: " + score);
System.out.println("Final count: " + count);
}
}
Note: Only post-form (x++, x–) is in scope for the AP CSA exam. Prefix forms (++x, –x) are NOT tested.
Code Examples
A. Simple: Individual Compound Operators
// CODE_RUNNER: Compound Operators Basic
// Run it, then change a value and predict the new output
public class CodeRunner2_CompoundOperatorsBasic {
public static void main(String[] args) {
int num = 10;
// Addition assignment
num += 5;
System.out.println("After += 5: " + num); // 15
// Subtraction assignment
num -= 3;
System.out.println("After -= 3: " + num); // 12
// Multiplication assignment
num *= 2;
System.out.println("After *= 2: " + num); // 24
// Division assignment
num /= 4;
System.out.println("After /= 4: " + num); // 6
// Remainder assignment
num %= 5;
System.out.println("After %= 5: " + num); // 1
}
}
B. Intermediate: Increment/Decrement in Expressions
// CODE_RUNNER: Increment and Decrement Demo
// Run it, then change a value and predict the new output
public class CodeRunner3_IncrementDecrement {
public static void main(String[] args) {
// Post-increment returns OLD value
int x = 5;
int y = x++;
System.out.println("x = " + x + ", y = " + y); // x = 6, y = 5
// Post-decrement returns OLD value
int a = 10;
int b = a--;
System.out.println("a = " + a + ", b = " + b); // a = 9, b = 10
// Multiple increments in an expression
int count = 0;
int total = count++ + count++ + count++;
System.out.println("count = " + count); // count = 3
System.out.println("total = " + total); // total = 0 + 1 + 2 = 3
// Compound operators with other operations
int score = 100;
score += 50; // score = 150
score -= score / 5; // score = 150 - 30 = 120
System.out.println("Final score: " + score); // 120
}
}
C. Complex: Real-World Game State Simulator
// CODE_RUNNER: Game State Simulator
// Run it, then change a value and predict the new output
public class CodeRunner4_GameStateSimulator {
public static void main(String[] args) {
// Initial state
int health = 100;
int mana = 50;
int experience = 0;
int level = 1;
int enemiesDefeated = 0;
double damageMultiplier = 1.0;
System.out.println("=== GAME STATE SIMULATOR ===");
System.out.println("Starting: Health=" + health +
", Mana=" + mana +
", Level=" + level + "\n");
// Event 1: Take damage
System.out.println("Event 1: Enemy attacks for 15 damage");
health -= 15;
System.out.println("Health now: " + health + "\n");
// Event 2: Cast spell (costs mana)
System.out.println("Event 2: Cast fireball spell (-20 mana)");
mana -= 20;
experience += 25;
enemiesDefeated++;
System.out.println("Mana: " + mana + ", XP: " + experience + "\n");
// Event 3: Level up (requires 100 XP)
if (experience >= 100) {
System.out.println("Event 3: LEVEL UP!");
level++;
health += 25; // Health restore on level up
mana *= 2; // Double mana on level up
damageMultiplier *= 1.15; // 15% damage increase
experience = 0; // Reset XP for next level
System.out.println("New level: " + level);
System.out.println("Health restored: " + health);
System.out.println("Mana doubled: " + mana);
System.out.println("Damage multiplier: " + damageMultiplier + "\n");
}
// Event 4: Potion usage
System.out.println("Event 4: Use healing potion");
health += 30;
health = health > 100 ? 100 : health; // Cap at 100
System.out.println("Health: " + health + "\n");
// Event 5: Critical hit bonus
System.out.println("Event 5: Critical hit! Enemies defeated and XP bonus");
enemiesDefeated++;
experience += experience / 2; // 50% XP bonus
// Final state
System.out.println("\n=== FINAL STATE ===");
System.out.println("Level: " + level);
System.out.println("Health: " + health);
System.out.println("Mana: " + mana);
System.out.println("Experience: " + experience);
System.out.println("Enemies Defeated: " + enemiesDefeated);
System.out.println("Damage Multiplier: " + String.format("%.2f", damageMultiplier));
}
}
Hacks & Practice Tasks
Popcorn Hack
3-minute challenge: Transform verbose code into compound operators.
Task: Rewrite the following code using compound assignment operators and increment operators:
// CODE_RUNNER: Basic Game Score Simulator
// Run it, then change a value and predict the new output
public class CodeRunner5_BasicGameScore {
public static void main(String[] args) {
int playerScore = 1000;
int playerHealth = 100;
int enemiesDefeated = 0;
// Player defeats an enemy worth 250 points
playerScore = playerScore + 250;
// Player takes 15 damage
playerHealth = playerHealth - 15;
// Enemy count goes up
enemiesDefeated = enemiesDefeated + 1;
// Boss battle: double the current score
playerScore = playerScore * 2;
// Healing potion restores 80% effectiveness
// First multiply by 4, then divide by 5
playerHealth = playerHealth * 4;
playerHealth = playerHealth / 5;
System.out.println("Score: " + playerScore);
System.out.println("Health: " + playerHealth);
System.out.println("Enemies Defeated: " + enemiesDefeated);
}
}
Solution Skeleton:
// CODE_RUNNER: Game Score with Compound Operators
// Run it, then change a value and predict the new output
public class CodeRunner6_GameScoreCompound {
public static void main(String[] args) {
int playerScore = 1000;
int playerHealth = 100;
int enemiesDefeated = 0;
// Rewrite each line using compound operators
// playerScore = playerScore + 250; becomes:
playerScore += 250;
// playerHealth = playerHealth - 15; becomes:
playerHealth -= 15;
// enemiesDefeated = enemiesDefeated + 1; becomes:
enemiesDefeated++;
// playerScore = playerScore * 2; becomes:
playerScore *= 2;
// playerHealth = playerHealth * 4; playerHealth = playerHealth / 5; becomes:
playerHealth *= 4;
playerHealth /= 5;
// Print the results
System.out.println("Score: " + playerScore);
System.out.println("Health: " + playerHealth);
System.out.println("Enemies: " + enemiesDefeated);
}
}
Homework Hack
Task: Create a simulation program for ONE of the following scenarios. Your program must use at least three different compound assignment operators and demonstrate state changes with print statements after each operation.
Choose ONE Scenario:
Option A: Bank Account Manager
Simulate a personal bank account over time:
// CODE_RUNNER: Bank Account Manager
// Run it, then change a value and predict the new output
public class CodeRunner7_BankAccountManager {
public static void main(String[] args) {
double balance = 1000.0;
int transactions = 0;
double totalInterest = 0.0;
double totalFees = 0.0;
System.out.println("=== BANK ACCOUNT SIMULATOR ===\n");
System.out.println("Starting Balance: $" + balance + "\n");
// Month 1: Salary deposit
System.out.println("Month 1: Salary deposited");
balance += 3000.0;
transactions++;
System.out.println("Balance: $" + balance + "\n");
// Rent payment
System.out.println("Rent payment");
balance -= 1200.0;
transactions++;
System.out.println("Balance: $" + balance + "\n");
// Interest earned
System.out.println("Interest applied (0.5%)");
totalInterest += balance * 0.005;
balance += totalInterest;
System.out.println("Interest earned: $" + totalInterest);
System.out.println("Balance: $" + balance + "\n");
// Month 2: Fee assessment
System.out.println("Month 2: Monthly maintenance fee");
totalFees += 5.0;
balance -= totalFees;
System.out.println("Balance: $" + balance + "\n");
// Multiple small purchases
System.out.println("Groceries and utilities");
balance -= 150.0;
transactions++;
System.out.println("Balance: $" + balance + "\n");
// Final Summary
System.out.println("=== FINAL SUMMARY ===");
System.out.println("Final Balance: $" + balance);
System.out.println("Total Transactions: " + transactions);
System.out.println("Total Interest Earned: $" + totalInterest);
System.out.println("Total Fees Paid: $" + totalFees);
}
}
Option B: Fitness Progress Tracker
Track fitness metrics over time:
// CODE_RUNNER: Fitness Tracker
// Run it, then change a value and predict the new output
public class CodeRunner8_FitnessTracker {
public static void main(String[] args) {
int totalCalories = 0;
int workoutDays = 0;
double totalSteps = 0.0;
int weekNumber = 1;
System.out.println("=== FITNESS TRACKER ===\n");
// Week 1: Baseline week
System.out.println("Week " + weekNumber + ": Starting fitness journey");
totalCalories += 2000; // Daily average 2000 cal/day
workoutDays += 3; // Worked out 3 days
totalSteps += 50000; // 50k steps
System.out.println("Workouts: " + workoutDays + " days, Steps: " +
(int)totalSteps + ", Calories: " + totalCalories + "\n");
// Week 2: Increased effort
weekNumber++;
System.out.println("Week " + weekNumber + ": Increased intensity");
totalCalories += 2500;
workoutDays++; // One more workout day
totalSteps += 65000; // 30% more steps
System.out.println("Workouts: " + workoutDays + " days, Steps: " +
(int)totalSteps + ", Calories: " + totalCalories + "\n");
// Week 3: Breakthrough week
weekNumber++;
System.out.println("Week " + weekNumber + ": New personal records!");
totalCalories += 2200;
workoutDays++; // 5 workouts this week
totalSteps *= 1.2; // 20% increase from momentum
System.out.println("Workouts: " + workoutDays + " days, Steps: " +
(int)totalSteps + ", Calories: " + totalCalories + "\n");
// Final Summary
System.out.println("=== PROGRESS SUMMARY ===");
System.out.println("Weeks Completed: " + weekNumber);
System.out.println("Total Workout Days: " + workoutDays);
System.out.println("Total Steps: " + (long)totalSteps);
System.out.println("Total Calories: " + totalCalories);
System.out.println("Average Daily Calories: " + (totalCalories / (weekNumber * 7)));
}
}
Requirements for your implementation:
- Use at least 3 different compound assignment operators
- Include at least 5 state-changing events
- Print the value after each operation
- Add comments explaining each compound operator choice
- Test your code and verify output is correct
References
Reference List
College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description.pdf
Gosling, J., Joy, B., Steele, G., Bracha, G., & Buckley, A. (2023). The Java language specification: Java SE 21 edition (§15.26.2, Compound Assignment Operators). Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html
Outside Academic Reference
The equivalence between a compound operator and its “long form” — the core idea of this lesson’s Tech Talk — is formally specified in the Java Language Specification: “A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once” (Gosling et al., 2023, §15.26.2).