Apex gives you four basic arithmetic operators for working with numbers. You will use them constantly, from adding up order totals to computing discounts.
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 4 + 3 | 7 |
| - | Subtraction | 9 - 5 | 4 |
| * | Multiplication | 6 * 2 | 12 |
| / | Division | 8 / 2 | 4 |
Just like in math class, multiplication and division happen before addition and subtraction:
Integer result = 2 + 3 * 4; // 14, not 20
Apex evaluates 3 * 4 first and then adds 2. When you want a different order, use parentheses:
Integer result = (2 + 3) * 4; // 20
Parentheses are also a great way to make your intent obvious to other developers, even when they are not strictly required.
When an expression mixes an Integer with a Decimal, the result becomes a Decimal so no precision is lost:
Decimal price = 9.99; Integer quantity = 3; Decimal subtotal = price * quantity; // 29.97 (Decimal)
Here is a short example that computes an order total:
Decimal unitPrice = 4.50; Integer quantity = 3; Decimal shippingFee = 2.25; Decimal total = unitPrice * quantity + shippingFee; System.debug(total); // 15.75
Because * runs before +, the unit price and quantity are multiplied first and the shipping fee is added last, which is exactly what we want.