Sub topic 15
Assignment and compound assignment
This chapter assumes you can declare typed variables, know the primitive types, and understand null as covered in earlier chapters. It covers how = and the compound operators (+=, -=, and so on) behave. It also covers how assignment differs between primitives and collections, and the errors you are most likely to hit.
The basic assignment operator
The = operator evaluates the right side, checks that the result fits the type on the left, and stores it. Apex checks that fit when it compiles your code, so a mismatch is a compile error, not a runtime surprise.
Integer count = 5;
Long big = count; // implicit widening, allowed
Decimal exact = big; // Long to Decimal, allowed
// Integer back = big; // compile error: Long does not fit Integer
Integer back = (Integer) big; // not valid for primitives; use a conversion methodThe last line above is a trap. Casting with (Integer) does not narrow numeric primitives in Apex. Use Integer.valueOf(big) instead, or Decimal.intValue() for a Decimal. A runnable version:
Long big = 42L;
Integer narrowed = Integer.valueOf(big);
Decimal price = 19.99;
Integer whole = price.intValue();
System.debug(narrowed + ' ' + whole);This prints 42 19. intValue() drops the fraction and does not round.
Assignment is an expression
An assignment produces the value that was stored. Because = is right-associative, you can chain it:
Integer a;
Integer b;
Integer c;
a = b = c = 7;
System.debug(a + ' ' + b + ' ' + c);Apex evaluates c = 7 first, then b = 7, then a = 7. Chained assignment works, but separate statements are usually easier to read.
Compound assignment operators
A compound operator combines an operation with an assignment. x += y means roughly x = x + y, with x evaluated once.
| Operator | Meaning | Typical use | Column |
|---|---|---|---|
| `+=` | add, or concatenate for String | counters, totals, building text | |
| `-=` | subtract | countdowns, balances | |
| `*=` | multiply | scaling | |
| `/=` | divide | averaging, ratios | |
| `&=` | bitwise AND | clearing flag bits | |
| `\ | =` | bitwise OR | setting flag bits |
| `^=` | bitwise XOR | toggling flag bits | |
| `<<=` | shift left | multiplying by powers of two | |
| `>>=` | shift right (sign preserved) | dividing by powers of two | |
| `>>>=` | unsigned shift right | bit patterns |
Apex has no %= operator, so write x = Math.mod(x, y) when you need a remainder.
Integer total = 10;
total += 5; // 15
total -= 3; // 12
total *= 2; // 24
Decimal avg = 10;
avg /= 4; // 2.5
String msg = 'Hello';
msg += ', ';
msg += 'Apex';
System.debug(total + ' ' + avg + ' ' + msg);The output is 24 2.5 Hello, Apex. I used Decimal for the division on purpose. Keep the left side's type in mind, because the result must still fit the variable you are assigning to.
Increment and decrement
++ and -- are the one-step forms. The position matters when you use the result inside a larger expression.
Integer i = 5;
Integer afterUse = i++; // afterUse is 5, i becomes 6
Integer beforeUse = ++i; // i becomes 7, beforeUse is 7
System.debug(afterUse + ' ' + beforeUse + ' ' + i);Used as a standalone statement (i++;), both forms behave the same.
Bit flags
The bitwise forms are rare in Apex, but they work on Integer and Long.
Integer flags = 1; // 0001
flags |= 4; // set bit: 0101 = 5
flags &= 5; // keep bits in mask 0101: still 5
flags ^= 1; // toggle bit 0: 0100 = 4
flags <<= 1; // shift left: 1000 = 8
System.debug(flags);Value copies versus reference copies
Assignment does different things depending on the type. Primitives hold the value itself, so assignment copies it. Collections and SObjects are objects, so assignment copies a reference, and both variables point at the same object.
Integer x = 1;
Integer y = x;
y += 10;
System.debug(x + ' ' + y); // 1 11
List<String> first = new List<String>{ 'a' };
List<String> second = first;
second.add('b');
System.debug(first.size()); // 2, same list
List<String> copy = first.clone();
copy.add('c');
System.debug(first.size() + ' ' + copy.size()); // 2 3clone() makes a shallow copy. The new list has its own slots, but if the elements are SObjects, both lists still point at the same records. The same applies to a SObject variable:
Account a1 = new Account(Name = 'Acme');
Account a2 = a1;
a2.Name = 'Globex';
System.debug(a1.Name); // Globex
Account a3 = a1.clone(false, true);
a3.Name = 'Initech';
System.debug(a1.Name); // still GlobexStrings are an exception to the object rule. They are immutable, so s += 'x' creates a new string and rebinds the variable. Other variables that held the old string are unaffected.
Common errors
Compound assignment on null
A null Integer cannot be updated with +=. The operation needs the current value, and null has none.
Integer total;
try {
total += 1;
} catch (NullPointerException e) {
System.debug('Caught: ' + e.getMessage());
}
total = 0;
total += 1;
System.debug(total);Always initialize accumulators. Strings behave differently: concatenating onto a null String does not throw, and the text null ends up in the result.
String s;
s += 'abc';
System.debug(s); // nullabcUpdating a map value
You cannot write counts.get(key) += 1, because get returns a value, not a variable. Read, change, and put back:
Map<String, Integer> counts = new Map<String, Integer>();
List<String> words = new List<String>{ 'a', 'b', 'a' };
for (String w : words) {
Integer current = counts.containsKey(w) ? counts.get(w) : 0;
counts.put(w, current + 1);
}
System.debug(counts);You can shorten the lookup with the null coalescing operator: counts.put(w, (counts.get(w) ?? 0) + 1);.
Reassigning a final variable
A final variable accepts exactly one assignment. A second one, including += or ++, is a compile error. For a final collection, the reference is fixed but the contents can still change.
final List<Integer> fixed = new List<Integer>();
fixed.add(1); // allowed
// fixed = new List<Integer>(); // compile error
// fixed += 1; // compile error
System.debug(fixed);Assignment inside a condition
Apex requires a Boolean in an if condition, so if (x = 5) fails to compile when x is an Integer. The risk remains for Boolean variables: if (isActive = true) compiles, assigns true, and always passes. Use == to compare.
Exercise
A trigger helper declares Integer retries; and later runs retries += 1;. What happens, and what is the fix?
Show answer
The statement throws a System.NullPointerException because retries is null and has no value to add to. Initialize it with Integer retries = 0; before using +=.
Exercise
Given List<Integer> a = new List<Integer>{ 1 }; List<Integer> b = a; b.add(2);, what is a.size(), and how would you change the code so a stays at size 1?
Show answer
a.size() is 2, because b = a copies the reference and both variables point at the same list. Use List<Integer> b = a.clone(); to get a separate shallow copy.
Exercise
What does this print? Integer i = 3; Integer r = i++ + 2; System.debug(r + ' ' + i);
Show answer
It prints 5 4. The postfix i++ yields the old value 3, so r is 3 + 2 = 5, and then i becomes 4.