Control Flow

Apex switch works on Integer, Long, String, sObject types, and enums.

8.1 if / else

Decimal amount = 12000;
if (amount > 10000) {
    System.debug('Large deal');
} else if (amount > 1000) {
    System.debug('Medium deal');
} else {
    System.debug('Small deal');
}

8.2 switch

Apex switch works on Integer, Long, String, sObject types, and enums. There is no fall-through and no break.

String when values are case-sensitive in switch, unlike ==.

String stage = 'Closed Won';
switch on stage {
    when 'Prospecting', 'Qualification' {
        System.debug('Early');
    }
    when 'Closed Won' {
        System.debug('Won!');
    }
    when null {
        System.debug('No stage');
    }
    when else {
        System.debug('In progress');
    }
}

// switch on sObject type — binds a typed variable
SObject rec = new Contact(LastName = 'Doe');
switch on rec {
    when Account a { System.debug('Account ' + a.Name); }
    when Contact c { System.debug('Contact ' + c.LastName); }
    when else      { System.debug('Other'); }
}

// switch on enum
switch on Trigger.operationType {   // inside a trigger
    when BEFORE_INSERT { /* ... */ }
    when AFTER_UPDATE  { /* ... */ }
    when else          { }
}

8.3 Loops

Never modify a collection (add/remove) while iterating over it with a for-each loop — it throws System.FinalException/ListException. Build a new collection instead.

// traditional for
for (Integer i = 0; i < 5; i++) { System.debug(i); }

// for-each over a collection
List<String> names = new List<String>{ 'Ann', 'Bob' };
for (String n : names) { System.debug(n); }

// while / do-while
Integer k = 0;
while (k < 3) { k++; }
do { k--; } while (k > 0);

// SOQL for loop — processes records in chunks of 200 (heap-friendly, see §15)
for (List<Account> chunk : [SELECT Id, Name FROM Account]) {
    System.debug('Chunk size: ' + chunk.size());
}

// break and continue
for (Integer i = 0; i < 10; i++) {
    if (i == 2) continue;
    if (i == 5) break;
}