Sub topic 14
Arithmetic operators
This chapter assumes you know the primitive types from earlier chapters (Integer, Long, Double, Decimal, String) and can run anonymous Apex in the Developer Console. It covers what each arithmetic operator does, which type the result has, and the cases that fail or surprise.
The operator set
Apex provides these arithmetic operators:
| Operator | Meaning | Applies to |
|---|---|---|
| `+` | Addition, string concatenation, date shift | Numbers, String, Date, Datetime, Time |
| `-` | Subtraction, unary negation | Numbers, Date, Datetime |
| `*` | Multiplication | Numbers |
| `/` | Division | Numbers |
| `++`, `--` | Increment, decrement by 1 | Integer, Long, Double, Decimal |
Apex has no % operator. Use Math.mod(dividend, divisor) for a remainder.
Integer a = 17;
Integer b = 5;
System.debug(a + b);
System.debug(a - b);
System.debug(a * b);
System.debug(Math.mod(a, b));
System.debug(-a);The output is 22, 12, 85, 2, and -17.
How the result type is chosen
When the operands have different numeric types, Apex widens to the broader one. The order from narrowest to broadest is Integer, Long, Double, Decimal. Adding an Integer to a Decimal gives a Decimal.
Integer qty = 3;
Decimal unitPrice = 2.50;
Decimal lineTotal = qty * unitPrice;
Long big = 2147483647L + 1;
System.debug(lineTotal);
System.debug(big);lineTotal is 7.50. big is 2147483648, which does not fit in an Integer. If both operands were Integers and the result exceeded 2147483647, the arithmetic would stay in Integer range and the value would not be what you expect. Declare at least one operand as Long when sums can grow large, for example when you total record counts or milliseconds.
Double versus Decimal
Double is a binary floating-point type. It cannot represent many decimal fractions exactly. Decimal stores base-10 digits, so it is exact for values such as prices.
Double d = 0.1 + 0.2;
Decimal m = 0.1 + 0.2;
System.debug(d);
System.debug(m);
System.debug(d == 0.3);
System.debug(m == 0.3);The Double result prints as 0.30000000000000004 and the equality check is false. The Decimal result is 0.3 and the check is true. Use Decimal for money and for any value you compare with ==. Salesforce Currency, Number, and Percent fields are returned to Apex as Decimal.
Scale and rounding
Decimal keeps track of scale, the count of digits after the decimal point. Multiplication adds the scales of the operands, so results can carry more digits than you want.
Decimal total = 10.00;
Decimal rate = 0.075;
Decimal raw = total * rate;
Decimal tax = raw.setScale(2, RoundingMode.HALF_UP);
System.debug(raw);
System.debug(tax);raw is 0.75000 and tax is 0.75. Always call setScale with an explicit RoundingMode before you store or display a currency value. Without a rounding mode, setScale throws an exception if it would have to discard non-zero digits.
Division
Division by zero throws a System.MathException with the message Divide by 0. Check the divisor first, or catch the exception.
Decimal numerator = 10;
Decimal denominator = 0;
Decimal result;
if (denominator != 0) {
result = numerator / denominator;
} else {
result = 0;
}
System.debug(result);For a non-terminating result such as one third, use the divide method so you control the precision:
Decimal third = Decimal.valueOf(1).divide(3, 4, RoundingMode.HALF_UP);
System.debug(third);This prints 0.3333. The three arguments are the divisor, the scale, and the rounding mode.
Null operands
Arithmetic on a null number throws a System.NullPointerException. This is a common error when a field is empty, because an unset Number field is null, not zero.
Integer bonus = null;
Integer base = 100;
Integer safeBonus = bonus ?? 0;
System.debug(base + safeBonus);The ?? operator (covered in a later chapter) supplies a default. Without it, base + bonus would throw.
Increment and decrement
++ and -- change a variable by one. The position decides what the expression itself evaluates to:
- Prefix (
++n) changes the variable first, then yields the new value. - Postfix (
n++) yields the old value, then changes the variable.
Integer n = 5;
Integer post = n++;
Integer pre = ++n;
System.debug(post);
System.debug(pre);
System.debug(n);The output is 5, 7, and 7. When you only need to count, write n++; on its own line. Mixing increments into larger expressions makes code harder to read.
The + operator is overloaded
With a String on either side, + concatenates. The operands are converted to text, so evaluation order matters when you mix numbers and strings. Apex evaluates + from left to right.
System.debug(1 + 2 + ' items');
System.debug('items: ' + 1 + 2);
System.debug('items: ' + (1 + 2));The output is 3 items, items: 12, and items: 3. Parenthesize arithmetic that sits inside a string expression.
Date arithmetic
Adding an Integer to a Date or Datetime moves it forward by that many days. Subtracting works the same way. To get the number of days between two dates, use daysBetween.
Date start = Date.newInstance(2026, 11, 30);
Date later = start + 7;
System.debug(later);
System.debug(start.daysBetween(later));This prints 2026-12-07 and 7. Date and Datetime values are covered in their own chapter.
Common errors
- Using
%. The compiler rejects it. CallMath.mod. - Storing money in Double. Rounding noise appears in totals and equality checks fail.
- Dividing by a field that can be zero or null. Check both.
- Letting Integer arithmetic overflow. Promote one operand to Long.
- Writing
'Total: ' + a + band expecting a sum.
Exercise
A Number field Discount__c may be null. Write an expression that computes price - discount as a Decimal, treating a null discount as zero, and explain why price - Discount__c alone is risky.
Show answer
Use Decimal result = price - (discount ?? 0);. The expression price - discount throws a System.NullPointerException when discount is null, because arithmetic does not treat null as zero. The ?? operator substitutes 0 before the subtraction happens.
Exercise
What do System.debug(2 + 3 + 'x') and System.debug('x' + 2 + 3) print, and why?
Show answer
The first prints 5x and the second prints x23. Apex evaluates + left to right. In the first case 2 + 3 is added as numbers before the String is reached. In the second case the left side is already a String, so each number is appended as text.