Variables, Constants & Operators
Unlike Java 10+, Apex has no var keyword — every variable has an explicit type.
7.1 Variables and scope
Unlike Java 10+, Apex has no var keyword — every variable has an explicit type. Variables are block-scoped; you cannot redeclare a variable name in a nested block of the same method.
Integer count = 0; // declaration + initialization
String a, b, c; // multiple declarations (all null)
Decimal total = 0, tax = 0;7.2 Constants
final prevents reassignment, but a final collection's contents can still change.
public class TaxCalculator {
public static final Decimal VAT_RATE = 0.20; // constant
public static final Set<String> EU_CODES = new Set<String>{ 'DE', 'FR', 'IT' };
private final String region; // set once (in declaration or constructor)
public TaxCalculator(String region) {
this.region = region;
}
}7.3 Operators
No % operator — use Math.mod(a, b) Also |= &= <<= >>= >>>=
== on strings is case-insensitive; use equals() for case-sensitive Reference equality for objects cond ? a: b
Returns null instead of throwing NullPointerException Returns a unless it is null, else b (Spring '24+) On Integer/Long 'Total: ' + 5 → 'Total: 5' obj instanceof Account
String s1 = 'Hello', s2 = 'HELLO';
System.debug(s1 == s2); // true (case-insensitive!)
System.debug(s1.equals(s2)); // false (case-sensitive)
Integer remainder = Math.mod(17, 5); // 2
Account acc = null;
String nm = acc?.Name; // null, no exception
String display = acc?.Name ?? 'Unknown'; // 'Unknown'
Integer score = 72;
String grade = score >= 90 ? 'A' : score >= 70 ? 'B' : 'C';