Unit 1.6: Compound Assignment Operators

AP Computer Science A

Learning to use shortcuts for common operations

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.

What are Compound Assignment Operators?

Compound assignment operators are shortcuts that combine an arithmetic operation with assignment.

Traditional Way:

x = x + 5; y = y - 3; z = z * 2;

Compound Assignment Way:

x += 5; y -= 3; z *= 2;

Same result, cleaner code!

The Five Compound Assignment Operators

+=

Addition Assignment

x += 5 means x = x + 5

-=

Subtraction Assignment

x -= 3 means x = x - 3

*=

Multiplication Assignment

x *= 2 means x = x * 2

/=

Division Assignment

x /= 4 means x = x / 4

%=

Modulus Assignment

x %= 3 means x = x % 3

Step-by-Step Example

Let's trace through some compound assignments:

int score = 10; score += 5; // score = score + 5 = 10 + 5 = 15 score *= 2; // score = score * 2 = 15 * 2 = 30 score -= 8; // score = score - 8 = 30 - 8 = 22 score /= 2; // score = score / 2 = 22 / 2 = 11 score %= 3; // score = score % 3 = 11 % 3 = 2 System.out.println(score); // Output: 2

Final value of score: 2

Post-Increment and Post-Decrement Operators

Special operators for adding or subtracting exactly 1:

++

Post-Increment

x++ means x = x + 1

int count = 5; count++; // count is now 6
--

Post-Decrement

x-- means x = x - 1

int lives = 3; lives--; // lives is now 2

AP Exam Note:

Only post-fix form (x++, x--) is tested. Pre-fix form (++x, --x) is outside the scope.

Common Mistakes to Avoid

Wrong

int x = 5; 5 += x; // ERROR! Can't assign to a literal int y = 10; y =+ 3; // This is y = (+3), not y += 3!

Correct

int x = 5; x += 5; // x becomes 10 int y = 10; y += 3; // y becomes 13

Remember:

  • The variable must be on the LEFT side of the operator
  • Don't confuse += with =+
  • Compound operators can only be used with variables, not literals
  • The result is always stored back in the original variable

Practice Problems

What will be the final values?

// Problem 1 int a = 8; a += 4; a *= 3; a -= 10; // What is the value of a? // Problem 2 int b = 15; b %= 4; b++; b /= 2; // What is the value of b? // Problem 3 int c = 20; c -= 5; c++; c *= 2; c %= 7; // What is the value of c?

Answers:

Problem 1: a = 26 (8+4=12, 12*3=36, 36-10=26)

Problem 2: b = 2 (15%4=3, 3+1=4, 4/2=2)

Problem 3: c = 4 (20-5=15, 15+1=16, 16*2=32, 32%7=4)

1 / ?