java-foundations 15 min read

Compound Assignment & Increment

Shorthand operators for the things you do to variables most often — and the accumulation patterns that appear in every program

Reading: Reges & Stepp: Ch. 2 §2.2

Part 1 — Compound Assignment Operators

The five compound assignment operators combine an operation with an assignment in one step.

The full set

Shorthand Equivalent What it does
x += 3 x = x + 3 Add 3 to x
x -= 5 x = x - 5 Subtract 5 from x
x *= 2 x = x * 2 Multiply x by 2
x /= 4 x = x / 4 Divide x by 4 (int rules apply!)
x %= 3 x = x % 3 Set x to remainder of x ÷ 3
int balance = 1000;
balance += 200;     // deposit:    1200
balance -= 75;      // withdrawal:  1125
balance *= 2;       // double it:  2250
balance /= 3;       // thirds:     750  (integer division!)
balance %= 100;     // remainder:  50

Each line reads exactly what it does: “add 200 to balance”, “subtract 75 from balance.” That clarity is why compound operators exist.

Why compound operators are safer

Consider these two ways to add price to total:

total = total + price;    // if you mistype: total = toal + price → compile error
total += price;           // no repetition, no typo risk

The expanded form repeats the variable name. If you misspell it on the right side, you get a compile error — or worse, silently use a different variable. Compound assignment eliminates the repetition.

Works with double too

double balance = 1000.00;
balance += 50.00;      // deposit:  1050.00
balance -= 25.50;      // payment:  1024.50
balance *= 1.05;       // interest: 1075.725

System.out.printf("Balance: $%.2f%n", balance);   // Balance: $1075.73

Part 2 — Accumulation Patterns

The most important use of += is building a running total: start at zero, add each item, end with the sum.

int total = 0;       // accumulator — always starts at the "empty" value

total += 88;         // first score
total += 72;         // second score
total += 95;         // third score
total += 55;         // fourth score
total += 87;         // fifth score

System.out.println("Total: " + total);   // Total: 397

This pattern works for any kind of accumulation:

Goal Starting value Operator
Sum of values 0 +=
Count of events 0 ++
Running product 1 *=
Running minimum first value = Math.min(...)

Week 3 preview: When you learn loops, this same pattern runs inside the loop body. Instead of writing total += s1; total += s2; ... five times, you will write total += score once and let the loop repeat it. The pattern is identical — the loop just drives the repetition.


Part 3 — Increment and Decrement

++ adds 1. -- subtracts 1. That is all they do.

int count = 0;
count++;    // 1
count++;    // 2
count++;    // 3
count--;    // 2

System.out.println("Count: " + count);   // Count: 2

Counting events

The canonical use: count how many times a condition was true.

int s1 = 88, s2 = 72, s3 = 95, s4 = 55, s5 = 87;
int passingCount = 0;

if (s1 >= 60) passingCount++;
if (s2 >= 60) passingCount++;
if (s3 >= 60) passingCount++;
if (s4 >= 60) passingCount++;
if (s5 >= 60) passingCount++;

System.out.println("Passing: " + passingCount);   // Passing: 4

passingCount++ is passingCount = passingCount + 1 in three fewer characters. When you see count++, you know immediately: “something is being counted.”


Part 4 — Pre vs. Post: When Does It Matter?

x++ and ++x both add 1 to x. The difference: when the increment happens relative to the value being read.

As a standalone statement: no difference

int a = 5;
a++;     // a is now 6
++a;     // a is now 7
// Both just add 1. Order doesn't matter here.

Inside an expression: the difference emerges

int x = 5;

int a = x++;   // post-increment: use x (5) first, then increment
               // a = 5, x = 6

int b = ++x;   // pre-increment: increment first, then use x
               // x = 7, b = 7

Post-increment (x++): the current value of x is used in the expression, then x is incremented.

Pre-increment (++x): x is incremented first, then the new value is used in the expression.

A concrete trace
int x = 10;
System.out.println(x++);   // prints 10, then x becomes 11
System.out.println(x);     // prints 11
System.out.println(++x);   // x becomes 12, then prints 12
System.out.println(x);     // prints 12

Output: 10, 11, 12, 12

Practical advice: In lab code, use ++ and -- only as standalone statements (on their own line), never inside a larger expression. The pre/post distinction only matters when embedded in expressions — and embedding them creates code that’s hard to read and easy to get wrong.

Check Your Understanding
What does this print?
int x = 3;
x += 2;
x *= x;
System.out.println(x);
A11
B15
C25
D10
Answer: C. Step by step: x = 3. Then x += 2x = 5. Then x *= xx = x * x = 5 * 5 = 25. Each compound operator uses the current value of x on the right side.

Part 5 — String Concatenation with +=

+= also works on Strings. It appends text to the end:

String output = "";
output += "Name: Alice";
output += "\n";
output += "Score: 95";
System.out.println(output);
Name: Alice
Score: 95

This is the same as output = output + "Name: Alice" — just shorter. You will use this pattern to build multi-line output once you reach loops.


Part 6 — Lab 4 CP3 Pattern

Here is the compound-operator pattern for the paycheck lab:

double netPay   = grossPay;           // start: net = gross
double taxAmount = netPay;            // copy of gross
taxAmount *= (taxRate / 100);         // *= : taxAmount = taxAmount * 0.15 = 120.0
netPay -= taxAmount;                  // -= : netPay = 800.0 - 120.0 = 680.0

Each line reads exactly what it does. Compare to the long form:

taxAmount = taxAmount * (taxRate / 100);   // same thing, more to type
netPay    = netPay - taxAmount;            // same thing, more to type

Both are correct. The compound form is what the test looks for (*= and -= in source).


What You Learned

  • Compound operators (+=, -=, *=, /=, %=) are shorthand for x = x OP value — they’re clearer and eliminate variable-name repetition
  • += with int total = 0 is the accumulation pattern: start at zero, add each value
  • ++ and -- increment and decrement by exactly 1; use them standalone to count events
  • Pre-increment (++x) increments before using the value; post-increment (x++) uses then increments — only matters inside expressions
  • += works on Strings too: appends to the end

What Comes Next

Next: boolean expressions and branchingtrue/false, &&, ||, !, and how they connect to if/else decisions. This is the logic engine behind every program that responds differently to different inputs.