Sub topic 14
Assignment and compound assignment
This chapter assumes you know how to declare Apex variables, that Apex is strongly typed, and that you can run anonymous Apex in the Developer Console or an IDE. It builds on the arithmetic operators and covers how Apex stores values in variables and updates them in place.
The assignment operator
The = operator evaluates the expression on its right and stores the result in the variable on its left. The value must be compatible with the variable's declared type. Apex widens some types implicitly, such as Integer to Long to Decimal. It rejects anything that could lose information without a cast.
final Integer MAX_RETRIES = 3;
Integer attempts = 0;
attempts += 1;
System.debug(attempts < MAX_RETRIES);Here attempts += 1 is a compound assignment. The result is true because 1 is less than 3.
Compound assignment operators
A compound assignment combines an operation with an assignment. x += 1 means x = x + 1, but it names the variable only once.
| Operator | Meaning | Example | Column | Column |
|---|---|---|---|---|
| `+=` | add and assign | `total += 5` | ||
| `-=` | subtract and assign | `total -= 5` | ||
| `*=` | multiply and assign | `total *= 2` | ||
| `/=` | divide and assign | `total /= 2` | ||
| `&=`, `\ | =`, `^=` | bitwise and, or, xor, then assign | `flags \ | = 4` |
| `<<=`, `>>=`, `>>>=` | shift, then assign | `flags <<= 1` |
The += operator also works on Strings, where it appends text.
String message = 'Order';
message += ' shipped';
Decimal balance = 100.00;
balance *= 1.1;
balance -= 10;
System.debug(message + ' ' + balance);The example prints Order shipped 100.000. The multiplication gives 110.000, and subtracting 10 leaves 100.000. Decimal keeps the extra scale from 1.1.
Increment and decrement
The ++ and -- operators add or subtract 1. They work on numeric variables. A prefix form (++i) changes the value before the expression uses it. A postfix form (i++) uses the old value first.
Integer i = 5;
Integer a = i++;
Integer b = ++i;
System.debug(a + ' ' + b + ' ' + i);This prints 5 7 7. The first line stores 5 in a and raises i to 6. The second raises i to 7 and stores 7 in b.
Assignment chains and types
Assignments are expressions, so you can chain them. They evaluate from right to left.
Integer x;
Integer y;
x = y = 10;
System.debug(x + ' ' + y);Compound assignment still obeys type rules. If you assign a Decimal result back to an Integer, Apex raises a compile error. Convert it first, for example with Integer.valueOf().
Integer units = 10;
Decimal rate = 1.5;
Decimal cost = units;
cost *= rate;
System.debug(cost);Common errors
- Using
=where you meant==. In a condition such asif (x = 5), this fails to compile for non-Boolean values. For Boolean variables it can compile and silently assign. - Using a compound operator on a variable that is
null.Integer total; total += 1;throws aNullPointerExceptionbecausetotalholds no value yet. Initialize numeric variables before updating them. - Trying to assign to a
finalvariable a second time. The compiler rejects it. - Expecting
+=to add numbers to a String without thinking about order.'a' += 1is not valid, butString s = 'a'; s += 1;yieldsa1.
Exercise
What do a, b, and n hold after this code runs? Integer n = 4; Integer a = n--; Integer b = --n;
Show answer
a is 4, because the postfix form returns the old value before decrementing n to 3. b is 2, because the prefix form decrements n to 2 first and then returns it. n ends at 2.
Exercise
Why does Integer total; total += 10; fail at runtime, and how do you fix it?
Show answer
total is null because it was never initialized, and null cannot be used in arithmetic. Initialize it with Integer total = 0; before using +=.