The problem compound assignment solves
java
int score = 100;
score = score + 10; // add 10 to score
score = score - 5; // subtract 5 from score
score = score * 2; // double the score
Compound assignment operators
java
int score = 100;
score += 10; // score is now 110
score -= 5; // score is now 105
score *= 2; // score is now 210
score /= 3; // score is now 70 (integer division!)
score %= 6; // score is now 4 (70 % 6 = 4)
Increment and decrement operators
java
int count = 5;
count++; // count is now 6
count++; // count is now 7
count--; // count is now 6
Pre vs. Post — does it matter?
java
int a = 5;
int b = a++; // b = 5 (a's OLD value), then a becomes 6
int c = 5;
int d = ++c; // c becomes 6 FIRST, then d = 6
Tracing with compound assignment
java
int x = 10;
int y = 3;
x += y; // x = 10 + 3 = 13
y *= x; // y = 3 * 13 = 39
x -= 5; // x = 13 - 5 = 8
y %= x; // y = 39 % 8 = 7
System.out.println(x + " " + y); // Output: "8 7"
Compound assignment with Strings
java
String message = "Hello";
message += " World"; // message is now "Hello World"
message += "!"; // message is now "Hello World!"
System.out.println(message); // Output: "Hello World!"
AP Exam Tips
- •
- •
- •
- •
Common Mistakes
- •
- •
- •
- •