Sub topic 19
Operator precedence and grouping
This chapter assumes you know the arithmetic, comparison, and logical operators from the earlier chapters, and that you can run anonymous Apex in the Developer Console or an IDE. It covers how Apex decides which operator in an expression runs first, and when to override that order with parentheses.
Why precedence matters
An expression such as a + b * c > d && e contains several operators. Apex does not simply read left to right. It uses two rules:
- Precedence decides which operator applies first. An operator with higher precedence takes its operands before one with lower precedence.
- Associativity decides the order among operators of the same precedence. It is usually left to right, but assignment goes right to left.
If you misjudge either rule, the code still compiles and returns a wrong value. That is harder to catch than a compile error.
The precedence table
The table lists operators from highest precedence to lowest. This is the order given in the Apex Developer Guide.
| Level | Operators | Notes | Column | Column |
|---|---|---|---|---|
| 1 | `()` `{}` `++` `--` (postfix) | Grouping and postfix increment or decrement | ||
| 2 | `!` unary `-` unary `+` `(Type)` `new` | Prefix operators, casts, object creation | ||
| 3 | `*` `/` | Multiplication and division | ||
| 4 | `+` `-` | Addition, subtraction, string concatenation | ||
| 5 | `<` `<=` `>` `>=` `instanceof` | Relational comparison | ||
| 6 | `==` `!=` | Equality | ||
| 7 | `&&` | Logical AND | ||
| 8 | ` | ` | Logical OR | |
| 9 | `=` `+=` `-=` `*=` `/=` and other compound assignments | Right to left |
The ternary ?: and null coalescing ?? operators sit near the bottom, below the logical operators. The guide is the authority for their exact placement. In practice, parenthesize them, as described later in this chapter.
Arithmetic precedence
Multiplication and division run before addition and subtraction.
Integer a = 2 + 3 * 4;
Integer b = (2 + 3) * 4;
System.debug(a);
System.debug(b);The first line gives 14, because 3 * 4 runs first. The second gives 20, because the parentheses force 2 + 3 to run first.
Operators on the same level group from left to right. This matters for subtraction:
Integer left = 20 - 5 - 3;
Integer grouped = 20 - (5 - 3);
System.debug(left);
System.debug(grouped);Here left is 12, since Apex computes (20 - 5) - 3. grouped is 18.
Precedence with strings
The + operator both adds numbers and concatenates strings. Because it is left associative, the type of the left part decides what each + does.
String s1 = 'Total: ' + 1 + 2;
String s2 = 'Total: ' + (1 + 2);
String s3 = 1 + 2 + ' items';
System.debug(s1);
System.debug(s2);
System.debug(s3);The output is Total: 12, Total: 3, and 3 items. In s1, the first + already produces a String, so the second + concatenates 2 instead of adding it. In s3, 1 + 2 is evaluated first as numbers.
Comparison, equality, and logic
Relational operators (<, >) bind tighter than equality (==, !=). Both bind tighter than &&, and && binds tighter than ||.
Boolean x = true || false && false;
Boolean y = (true || false) && false;
System.debug(x);
System.debug(y);x is true because false && false runs first, giving true || false. y is false because the parentheses make the || run first.
A common mistake is mixing && and || without parentheses. Apex follows the table, but readers often assume left to right. Write the grouping out:
Boolean isVip = true;
Boolean isActive = false;
Boolean hasOverride = true;
Boolean canOrder = isVip && isActive || hasOverride;
Boolean canOrderClear = (isVip && isActive) || hasOverride;
System.debug(canOrder == canOrderClear);Both expressions give the same result. The second shows the intent, so the next reader does not need the table.
Unary operators bind first
! applies only to the value directly after it, not to the whole expression that follows.
Boolean a = true;
Boolean b = false;
System.debug(!a && b);
System.debug(!(a && b));The first line prints false, because it is (!a) && b. The second prints true, because a && b is false and ! flips it. Add parentheses whenever you negate a compound condition.
Assignment is right associative
Assignment operators group right to left, so a chain assigns from the right end first. A compound assignment evaluates its whole right side before it applies.
Integer p;
Integer q;
p = q = 7;
Integer total = 10;
total += 2 * 3;
System.debug(p + ' ' + q + ' ' + total);This prints 7 7 16. The statement total += 2 * 3 means total = total + (2 * 3), not (total + 2) * 3.
Ternary and null coalescing
The ?: operator has lower precedence than +. Concatenating before a ternary is a common source of errors:
Boolean isActive = true;
String status = 'Status: ' + (isActive ? 'on' : 'off');
System.debug(status);Without the parentheses, Apex would evaluate 'Status: ' + isActive first. That is a String, not a Boolean, so the ternary would fail to compile.
Chained ternaries group right to left, which makes a grade ladder work:
Integer score = 85;
String grade = score >= 90 ? 'A' : score >= 80 ? 'B' : 'C';
System.debug(grade);The result is B. Long chains are still hard to read, so prefer if/else beyond two levels.
For ??, keep the fallback inside its own parentheses so it applies to one value and not to a larger expression:
Integer bonus = null;
Integer pay = 100 + (bonus ?? 0);
System.debug(pay);This prints 100. The same applies to ?., which binds tightly to the object on its left, as . does.
Increment and decrement
Postfix i++ returns the old value, then increments. Prefix ++i increments, then returns the new value. Avoid using either inside a larger expression, because the result is hard to read. Put the increment on its own line.
Bitwise operators
The bitwise operators (&, |, ^, and shifts) are rarely needed in Apex. Do not rely on memorized precedence for them. Use parentheses around every bitwise sub-expression.
Practical rules
- Rely on the table only for the familiar cases:
*before+, comparison before&&, and&&before||. - Add parentheses whenever you mix
&&with||. - Parenthesize every
?:and??that sits inside a larger expression. - Parenthesize a
!applied to a compound condition. - Keep increments on their own statement.
Exercise
What do Integer r = 2 + 3 * 4 - 6 / 2; and String t = 1 + 2 + 'x' + 1 + 2; evaluate to?
Show answer
r is 11. 3 * 4 is 12 and 6 / 2 is 3, so the expression is 2 + 12 - 3 = 11. t is 3x12. 1 + 2 adds as numbers to 3, then + 'x' makes a String, and the remaining + operators concatenate 1 and 2.
Exercise
Given Boolean a = false; Boolean b = true; Boolean c = true;, what does a && b || c return? What does a && (b || c) return?
Show answer
The first returns true, because it is (a && b) || c, which is false || true. The second returns false, because b || c is true and a && true is false.