ACSA Exam Prep
Unit 1 · Using Objects and Methods · Topic 1.6

Compound Assignment Operators

Skill 3.A

Big idea: Compound operators are shorthand: x += 5 means x = x + 5. They follow the same type rules as the long form.

Learning objectives
  • Develop code for assignment statements with compound assignment operators and determine the value that is stored in the variable as a result.

The shorthand operators

ShorthandMeans
x += nx = x + n
x -= nx = x - n
x *= nx = x * n
x /= nx = x / n
x %= nx = x % n
x++x = x + 1
x--x = x - 1
Code
int x = 10;
x += 5;
x -= 3;
x *= 2;
x /= 5;
x %= 3;
x++;
System.out.println(x);
Output
2

Accumulators and counters

The most common use is building up a total or counting matches inside a loop. Start the total at 0 (or the count at 0), then add as you go. += also works on Strings to append text.

Code
int total = 0;
total += 4;
total += 9;
String s = "ab";
s += "cd";
System.out.println(total + " " + s);
Output
13 abcd
Key points
  • x op= n means x = x op n.
  • x++ adds 1; x-- subtracts 1.
  • /= on an int still does integer division.
Watch out
  • Trace each line in order; the variable's value changes after every statement.
Quick check
What is n?
int n = 7;
n *= 3;
n %= 4;
n--;
Show answer
0. 7 * 3 = 21, 21 % 4 = 1, then 1 - 1 = 0.
Not on the exam
  • Prefix form (++x).
  • Using ++ or -- inside other expressions, like arr[x++].