Sub topic 3
Arithmetic Operators and Expressions
Assume you know variables, conditionals, and basic Salesforce objects. Apex is strongly typed, so each expression must use compatible types.
Arithmetic operators
Use arithmetic operators with numeric values:
+adds values. It also joins strings.-subtracts.*multiplies./divides.%returns the remainder.
Use Decimal for exact currency calculations. Apex division with Decimal produces a Decimal.
Decimal subtotal = 80.00;
Decimal tax = (subtotal * 0.075).setScale(2, RoundingMode.HALF_UP);
Decimal total = subtotal + tax;
System.debug(total); // 86.00Assignment and compound assignment
The = operator assigns a value. Compound operators combine an operation with assignment:
count += 1meanscount = count + 1total -= discountquantity *= 2remainder %= 3
A variable declared with final can be assigned only once.
Comparison and equality
Comparison operators return Boolean values: ==, !=, <, >, <=, and >=.
Apex string == comparison ignores case. The equals method is case-sensitive.
String first = 'apex';
String second = 'APEX';
System.debug(first == second); // true
System.debug(first.equals(second)); // falseUse value == null to test for null. Calling a method on a null value causes a null reference error.
Logical operators and short-circuiting
Use && for “and,” || for “or,” and ! for “not.” These operators short-circuit. Apex evaluates the second condition only when it is needed.
List<Integer> items = null;
if (items != null && !items.isEmpty()) {
System.debug('Items exist');
}Ternary, safe navigation, and null coalescing
The ternary operator chooses between two values:
Integer score = 72;
String result = score >= 60 ? 'Pass' : 'Fail';
Account accountRecord = null;
String name = accountRecord?.Name;
String label = name ?? 'Unknown';?. returns null instead of dereferencing a null object. ?? uses its right-hand value when the left-hand value is null.
Operator precedence and grouping
Apex evaluates multiplication, division, and remainder before addition and subtraction. Comparisons occur before logical operators. Parentheses make intent clear:
Boolean allowed = (total > 100) && isActive;Bitwise operators
Bitwise operators work on integer bits. & performs AND, | performs OR, ^ performs XOR, and ~ complements bits. They are useful for flags and masks.
Integer permissions = 5; // binary 101
Integer readMask = 1; // binary 001
Boolean canRead = (permissions & readMask) != 0;
System.debug(canRead); // trueExercise
What does 18 / 4 produce when both operands are Integer values?
Show answer
It produces 4, because Integer division discards the fractional part. Use Decimal operands when you need a fractional result.