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
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;
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
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
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.