Lesson 1.6 · Unit 1 · CED topic 1.6

Compound assignment operators

Programs update variables constantly: add to a running total, count up one, halve a size. The statement total = total + price; does this, and it is so common that Java gives it a shorter form. This lesson is short on new ideas and long on payoff, because every loop you write from Unit 2 onward uses these operators.

Required content · LO 1.6.A

Learning objective.

  • 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.

Essential knowledge.

  • 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.
    Outside the course: The use of increment and decrement operators in prefix form (e.g., ++x) is outside the scope of the AP Computer Science A course and exam. The use of increment and decrement operators inside other expressions (e.g., arr[x++]) is outside the scope of the AP Computer Science A course and exam.

The compound assignment operators

A compound assignment operator combines an arithmetic operation with an assignment. It performs the operation between the value on the left and the value on the right, then assigns the result to the variable on the left.

Compound formSame asExampleIf x starts at 10, x becomes
x += 3x = x + 3add13
x -= 3x = x - 3subtract7
x *= 3x = x * 3multiply30
x /= 3x = x / 3divide (integer division for int)3
x %= 3x = x % 3remainder1

The right side is fully evaluated first, as a single value, and then the operation is applied. So x *= 2 + 3 means x = x * (2 + 3), not x = x * 2 + 3.

int x = 10;
x *= 2 + 3;
System.out.println(x);
50

Increment and decrement

Adding 1 or subtracting 1 is so common that it has its own operators. The post-increment operator ++ adds 1 to the stored value of a numeric variable, and the post-decrement operator -- subtracts 1. The new value is assigned to the variable.

int count = 5;
count++;
count++;
count--;
System.out.println(count);
6

On the exam, ++ and -- appear only as statements by themselves, in the postfix form. The prefix form (++count) and increments used inside other expressions (for example arr[i++]) are outside the course, so you will never have to decide what such a combination does.

Two patterns every program uses

An accumulator is a variable that builds up a result by repeating the same update: a running total, a product, a count. A counter is the special case that adds 1.

int total = 0;
total += 12;
total += 8;
total += 15;
int visits = 0;
visits++;
visits++;
System.out.println("total = " + total + ", visits = " + visits);
total = 35, visits = 2

Initialize an accumulator to the value that leaves the result unchanged: 0 for a sum, 1 for a product. Starting a sum at 1 makes every total one too big, a logic error that no tool will report.

Worked example · translating between forms

Rewrite each statement without a compound operator, and give the value of n if it starts at 20.

StatementEquivalentn afterward
n += 5;n = n + 5;25
n -= 8;n = n - 8;12
n *= 2;n = n * 2;40
n /= 3;n = n / 3;6
n %= 6;n = n % 6;2
n++;n = n + 1;21
int n = 20;
n /= 3;
System.out.println(n);
n %= 4;
System.out.println(n);
6
2

The division keeps only the integer part (20 / 3 is 6), and the remainder of 6 divided by 4 is 2.

Worked example · tracing a series of updates

Trace the code and give the final output.

int a = 3;
int b = 4;
a += b;
b *= a;
a -= b / 2;
b %= 5;
System.out.println(a + " " + b);
After the statementab
int a = 3; int b = 4;34
a += b;74
b *= a;728
a -= b / 2;-728
b %= 5;-73
-7 3

a -= b / 2 first computes 28 / 2 (14), then subtracts that from a: 7 - 14 is -7.

Worked example · a typing slip that still compiles

A student means to add 2 to x, but writes the operator the wrong way round.

int x = 10;
x =+ 2;
System.out.println(x);
2

The statement x =+ 2; is x = +2;: an ordinary assignment of the value positive 2. It compiles, it runs, and it quietly replaces the 10. The correct operator is +=, with the plus before the equals sign. Errors like this are logic errors, which is why you test with known answers and trace code instead of trusting it.

Exam focus

Questions here are tracing questions: a sequence of compound assignments, then "what is the value of x?" Be careful with /= on int values (truncation), with %=, and with a right side that is itself an expression (x *= 2 + 3). The postfix forms x++ and x-- are the only increment forms tested, and only as stand-alone statements.

Practice
  1. What is printed?
    int k = 8;
    k += 4;
    k /= 3;
    k -= 1;
    System.out.println(k);
    Show answer

    3. The value goes 8, 12, 4, then 3.

  2. What is printed?
    int p = 5;
    p *= 1 + 2;
    System.out.println(p);
    Show answer

    15. The right side 1 + 2 is evaluated to 3 first, so the statement is p = p * 3.

  3. Which statement is equivalent to score -= 3;?
    A.  score = 3 - score;
    B.  score = score - 3;
    C.  score =- 3;
    D.  score == score - 3;
    Show answer

    B. A reverses the subtraction, C assigns negative 3, and D is a comparison that changes nothing.

  4. What is printed?
    int n = 17;
    n %= 5;
    n++;
    n *= n;
    System.out.println(n);
    Show answer

    9. 17 % 5 is 2, n++ makes it 3, and n *= n is 3 * 3.

  5. Write statements that use a counter and an accumulator to count the values and add them up: 4, 9, and 2.
    int sum = 0;
    int count = 0;
    sum += 4;
    count++;
    sum += 9;
    count++;
    sum += 2;
    count++;
    System.out.println(sum + " " + count);
    Show answer

    The sum starts at 0, so the accumulator ends at 15, and the counter ends at 3. Initializing the sum to 0 leaves the first addition unchanged.

  6. A program is meant to compute 5 factorial (5 x 4 x 3 x 2 x 1) but prints 0. Find the bug.
    int result = 0;
    result *= 5;
    result *= 4;
    result *= 3;
    result *= 2;
    System.out.println(result);
    Show answer

    The accumulator for a product must start at 1, not 0. Anything times 0 is 0, so every update leaves it at 0.

← 1.5 Casting and the range of variables1.7 APIs, libraries, and documenting code →

Keep going in the full AP Computer Science A course

All of U1 (Using Objects and Methods) is free to everyone, with no account. The course has 58 lessons, each with worked examples and practice problems that come with full solutions. A free account can also start a free month of the whole course, with no card.

Open this lesson in the courseSee the whole course