Assignment Operators
By the end of this lesson, you'll be able to:
- Use = to assign a value to a variable
- Use compound assignment operators like += to update a variable based on its own value
- Explain why compound operators are considered better style than the long form
Prerequisites: "Arithmetic Operators"
Plain assignment
Integer caseCount = 0;
caseCount = caseCount + 1; // works, but there is a shorter way
Integer caseCount = 0;— starts the counter at0.caseCount = caseCount + 1;— readscaseCount's current value, adds1, and assigns the result back intocaseCount— the variable on both sides of=is the same one.
Compound assignment operators
Integer caseCount = 0;
caseCount += 1; // same as caseCount = caseCount + 1;
caseCount -= 1; // same as caseCount = caseCount - 1;
caseCount *= 2; // same as caseCount = caseCount * 2;
caseCount /= 2; // same as caseCount = caseCount / 2;
Integer caseCount = 0;— starts at0.caseCount += 1;—+=adds1tocaseCountand stores the result back, in one step.caseCount -= 1;— same idea, subtracting.caseCount *= 2;— same idea, multiplying.caseCount /= 2;— same idea, dividing.
Each combines an arithmetic operator with = into one step. += is by far the most common in real Apex code — you'll see it constantly once loops arrive in Module "Repeating Work: Loops."
A real business example: Case Management
Integer openCaseCount = 0;
openCaseCount += 1; // a new case just came in
Integer openCaseCount = 0;— no open cases yet.openCaseCount += 1;— one new case arrives, so the running total increases by1.
Running totals like this — counting cases, accumulating amounts — are one of the most common patterns you'll write, and += is the idiomatic way to express "add this to what's already there."
Best practices
- Prefer
+=over the long formx = x + 1whenever you're updating a variable based on its own current value — it's shorter, and once familiar, faster to read at a glance.
Exercise
Declare an Integer runningTotal starting at 100. Use compound assignment to add 50, then subtract 30, then double it. Debug the value after each step.
Show hint
runningTotal += 50; then runningTotal -= 30; then runningTotal *= 2;
Assignment Operators Quiz
Leaderboard
- 1. Monde Masiza 1/1
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
The = operator assigns a value to a variable. Compound assignment operators like += combine an arithmetic operation with assignment in one step — shorter to write and, once you're used to them, easier to read.