Skip to main content

1.6 Compound Assignment Operators

add to ChatGPT
Verified for the 2027 examUpdated October 2026Fiveable Content Team
Fiveable

💻AP Computer Science A Unit 1 Review

QR code for AP Computer Science A practice questions

1.6 Compound Assignment Operators

Compound assignment operators (+=, -=, *=, /=, %=) combine a math operation with assignment in one step, so score += 10 does the same thing as score = score + 10. The post-increment (x++) and post-decrement (x--) operators add or subtract 1 from a numeric variable, and you will see them often as loop counters. For AP Computer Science A, trace the variable value after each statement.

How Each Operator Updates the Variable

  • x += y is shorthand for x = x + y, and the same pattern holds for -=, *=, /=, and %=: do the operation between left and right, then store the result back in the left variable.
  • The variable must already be initialized before you use a compound assignment, because the operation needs the current value.
  • x++ adds 1 and x-- subtracts 1, and both store the new value back in the variable. The AP exam only uses the postfix form (x++, not ++x) and only as a standalone statement.
  • The right side is fully evaluated first, then the operation is applied. In x *= 2 + 3, the 2 + 3 happens first, so x is multiplied by 5.
  • Integer rules still apply: /= between two int values does integer division, and %= gives the remainder.
  • When you trace these in MCQs, write down the value after each line instead of doing it all in your head.

How Compound Assignment Operators Work

Math and Assignment Combined

The five compound assignment operators (+=, -=, *=, /=, %=) perform an operation and an assignment in one step. When you write total += price, it is exactly equivalent to total = total + price. The operator takes the current value, performs the operation with the right side, and stores the result back in the variable on the left.

These operators work with numeric variables (int and double in this course). Because they use the current value, the variable must already exist and hold a value first. You cannot use a compound assignment to declare a new variable.

What makes these operators handy is that they clearly show you are updating a value based on its current state. Code like balance -= payment immediately tells you that you are reducing balance by payment.

The += Operator

The += operator is the one you will see most because building up a total is such a common pattern. Whether you are summing numbers, tracking a score, or collecting points, += does the job: sum += num adds num to sum.

+= also works with strings for concatenation, which you will use more in Topic 1.15. Writing message += "!" appends an exclamation point. With strings, += produces a new String object because strings are immutable, while with numbers it simply updates the stored value.

Increment and Decrement

The ++ operator adds 1 to a variable, and -- subtracts 1. On the AP exam you will only see the postfix form: count++ or count--. These are equivalent to count += 1 and count -= 1.

These operators work on numeric variables, but you will almost always see them on int loop counters, which is exactly what counting needs. The prefix form (++x) and using these operators inside other expressions (like arr[x++]) are outside the scope of this course, so on the exam they show up alone as their own statement.

Order of Operations

The right side of a compound assignment is fully evaluated before the operation is performed. In x *= 2 + 3, the addition happens first (giving 5), then x is multiplied by 5. If you have total += calculateTax(price), the method runs first, then its return value is added to total.

This makes tracing predictable: everything to the right of the operator is calculated first, then the operation updates the variable.

Code Examples

Basic compound assignment operators in action:

</>Java
// Example: Basic compound assignment operators
public class ScoreTracker {
    public static void main(String[] args) {
        // Initialize variables
        int score = 100;
        double average = 85.5;
        int lives = 3;

        // Using += to add points
        score += 50;  // score is now 150
        System.out.println("Score after bonus: " + score);

        // Using -= to subtract
        score -= 25;  // score is now 125
        System.out.println("Score after penalty: " + score);

        // Using *= to multiply
        score *= 2;   // score is now 250
        System.out.println("Score after double multiplier: " + score);

        // Using /= to divide
        score /= 5;   // score is now 50
        System.out.println("Score after division: " + score);

        // Using %= for remainder
        score %= 15;  // score is now 5 (50 % 15)
        System.out.println("Score modulo 15: " + score);

        // Compound assignment with doubles
        average += 4.5;  // average is now 90.0
        average *= 1.1;  // 10% increase, average is now about 99.0 (floating-point rounding may show something like 99.00000000000001)
        System.out.println("New average: " + average);
    }
}

Increment and decrement:

</>Java
// Example: Increment and decrement operators
public class Counter {
    public static void main(String[] args) {
        int count = 0;

        // Post-increment - adds 1
        count++;  // count is now 1
        System.out.println("After count++: " + count);

        count++;  // count is now 2
        count++;  // count is now 3
        System.out.println("After three increments: " + count);

        // Post-decrement - subtracts 1
        count--;  // count is now 2
        System.out.println("After count--: " + count);

        // Common loop usage
        System.out.println("Counting up:");
        for (int i = 0; i < 5; i++) {
            System.out.println("i = " + i);
        }

        // Using increment in while loop
        int x = 0;
        while (x < 3) {
            System.out.println("x = " + x);
            x++;  // increment at end of loop
        }
    }
}

String concatenation with +=:

</>Java
// Example: String concatenation with +=
public class MessageBuilder {
    public static void main(String[] args) {
        String message = "Hello";

        // Build up a message
        message += " ";      // message is "Hello "
        message += "World";  // message is "Hello World"
        message += "!";      // message is "Hello World!"

        System.out.println(message);

        // Building a string in a loop
        String result = "";
        for (int i = 1; i <= 5; i++) {
            result += i;     // concatenates numbers as strings
            if (i < 5) {
                result += ", ";
            }
        }
        System.out.println("Numbers: " + result);  // "1, 2, 3, 4, 5"

        // Mixed types with +=
        String info = "Score: ";
        int points = 150;
        info += points;  // automatic conversion to string
        System.out.println(info);  // "Score: 150"
    }
}

Common Errors and Debugging

Using Compound Assignment Before Initialization

The variable must exist and have a value before you use a compound assignment:

</>Java
// ERROR: Variable not initialized
int total;
total += 10;  // Compiler error: variable total might not have been initialized

// CORRECT: Initialize first
int total = 0;
total += 10;  // Now total is 10

This error happens because compound assignment uses the current value. No current value means the operation cannot run.

Type Behavior with Compound Assignment

Watch how types interact:

</>Java
double precise = 100.0;
precise += 10;  // Works: the int is promoted to double

int count = 5;
count++;        // OK on an int counter

For AP CSA tracing, keep the type on the left in mind. If the left variable is a double, adding an int is fine because the value can be promoted to double. If the left variable is an int, avoid assuming that decimal values will fit cleanly back into it.

Forgetting That Operators Modify the Variable

A common mistake is forgetting these operators change the variable itself:

</>Java
int x = 5;
int y = x;
x += 3;  // x is now 8
System.out.println("x = " + x);  // 8
System.out.println("y = " + y);  // Still 5!

// The operators modify only the variable they're applied to

Copying x into y does not link them. Updating x later leaves y unchanged.

Practice Problems

Problem 1: What does this code print?

</>Java
int a = 10;
int b = 3;
a += b;
b *= 2;
a -= b;
System.out.println("a = " + a + ", b = " + b);

Solution:

  • Initial: a = 10, b = 3
  • a += b: a = 13, b = 3
  • b *= 2: a = 13, b = 6
  • a -= b: a = 7, b = 6
  • Prints: "a = 7, b = 6"

Problem 2: Build a string that displays a countdown:

</>Java
// Complete this method
public static String countdown(int start) {
    String result = "Countdown: ";
    // Your code here
    return result;
}
// countdown(5) should return "Countdown: 5 4 3 2 1 Blast off!"

Solution:

</>Java
public static String countdown(int start) {
    String result = "Countdown: ";
    for (int i = start; i > 0; i--) {
        result += i + " ";
    }
    result += "Blast off!";
    return result;
}

Problem 3: Fix this code that is trying to calculate compound interest:

</>Java
double balance = 1000;
double rate = 0.05;  // 5% interest
int years = 3;

for (int i = 0; i < years; i++) {
    balance + balance * rate;  // ERROR: This line is wrong
}
System.out.println("Final balance: " + balance);

Solution: Change the error line to use compound assignment:

</>Java
balance += balance * rate;  // Adds interest to balance
// Or equivalently:
balance *= (1 + rate);      // Multiplies balance by 1.05

Tracing and Writing Code With Compound Assignment

Code Tracing: When you see compound assignments in a multiple-choice question, work line by line and write the value of each variable after every statement. Chained operations like the Problem 1 example are easy to get right on paper but easy to slip on in your head. Slow down and track every change.

Free Response: Loops in free-response code writing almost always update a counter with i++. You will also reach for += to build running totals, like summing values as you traverse an array or ArrayList later in the course. Using these operators correctly keeps your loops clean and your accumulation logic clear.

Common Trap: Remember the exam only uses postfix x++ and x--, never the prefix ++x, and never embedded inside another expression. If a problem shows these operators, they appear as their own statement. Also keep integer division in mind: /= between two int values drops the fractional part.

Common Misconceptions

  • Misconception: x++ and ++x behave differently on the exam.
    Actually: The prefix form is not part of this course, so you only need the postfix x++ and x--, used as standalone statements.
  • Misconception: += only works with numbers.
    Actually: += does not only work with numbers. It also concatenates strings, producing a new String object each time because strings are immutable.
  • Misconception: Compound assignment skips the right-side math.
    Actually: Compound assignment does not skip the right-side math. The entire right side is evaluated first, then the operation updates the variable, so x *= 2 + 3 multiplies x by 5.
  • Misconception: These operators do not change the variable they are applied to.
    Actually: These operators change the variable they are applied to. Copying a value into another variable first does not keep the two in sync afterward.
  • Misconception: A compound assignment can initialize a variable.
    Actually: A compound assignment cannot initialize a variable. The variable must already hold a value, since the operation needs that current value to work.

Practice Questions for 1.6

1 of 10

Consider the following code segment.

</>Java
int num = /* some positive two-digit integer */;
int result = 0;

result += num % 10;
result *= 10;
num /= 10;
result += num;

Which of the following best describes the behavior of the code segment?

A.

It successfully appends a zero to the end of the original integer num.

B.

It successfully computes the sum of the two digits of the integer num.

C.

It successfully isolates the first digit of the original integer num.

D.

It successfully reverses the two digits of the original integer num.

Vocabulary

The following words are mentioned explicitly in the AP® course framework for this topic.

Term

Definition

assignment statement

A statement that stores a value in a variable using the assignment operator or a compound assignment operator.

compound assignment operator

Operators (+=, -=, *=, /=, %) that perform an arithmetic operation and assign the result to a variable in a single statement.

post-decrement operator

The -- operator used after a variable to subtract 1 from its stored value and assign the new value to the variable.

post-increment operator

The ++ operator used after a variable to add 1 to its stored value and assign the new value to the variable.

See Fiveable more often in Google

Mark Fiveable as a preferred source and Google is more likely to show you our guides in Top Stories, with a "preferred" badge in AI Mode and AI Overviews.

Prefer us on Google