Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 36 ยท Apex Basics

Control Flow and Loops in Apex

Learn Apex decision and loop statements: if/else, ternary, switch on values and types, for, for-each, while, do-while, break and continue, with stand-ins.

Programs make decisions and repeat work. Apex's control-flow statements will be familiar if you know Java, with two Salesforce twists: a switch statement that can match on SObject types, and SOQL for loops that stream big result sets safely. This lesson covers all of them.

if, else if, else

Java
Integer score = 72;
if (score >= 90) {
    System.debug('A');
} else if (score >= 70) {
    System.debug('B');
} else {
    System.debug('C');
}

Conditions must be Boolean. A null Boolean throws a NullPointerException in a condition, so initialise flags (Boolean ok = false;).

Logical operators: && (and), || (or), ! (not). They short-circuit: in a != null && a.length() > 3, the second test never runs when a is null. This is how you write safe null checks.

The ternary operator picks one of two values:

Java
String label = (score >= 70) ? 'pass' : 'fail';

There is also a safe navigation operator ?. that returns null instead of throwing when the left side is null: String city = account?.BillingCity;. And the null-coalescing operator ?? supplies a default: String shown = city ?? 'Unknown';.

switch

A switch statement compares one value against several when branches. There is no fall-through and no break needed:

Java
String stage = 'Closed Won';
switch on stage {
    when 'Prospecting', 'Qualification' {
        System.debug('early');
    }
    when 'Closed Won' {
        System.debug('celebrate');
    }
    when else {
        System.debug('other');
    }
}

It works with Integer, Long, String, Enum and, uniquely, SObject types:

Java
switch on record {
    when Account a { System.debug('Account ' + a.Name); }
    when Contact c { System.debug('Contact ' + c.LastName); }
    when else      { System.debug('something else'); }
}

for loops

The classic counting loop:

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

The for-each loop walks a list or set:

Java
for (Account acc : accounts) {
    acc.Description = 'Reviewed';
}

Prefer for-each when you do not need the index. It is shorter and cannot go out of bounds.

SOQL for loops

A SOQL for loop puts the query inside the loop header. Salesforce fetches the records in chunks of 200, so a huge result does not fill the heap:

Java
for (Account acc : [SELECT Id, Name FROM Account WHERE Industry = 'Energy']) {
    System.debug(acc.Name);
}

for (List<Account> batch : [SELECT Id FROM Account]) {
    // batch holds up to 200 records at a time
}

This is one query toward the limit, not one per row.

while and do-while

Java
Integer n = 10;
while (n > 0) {
    n = n - 3;          // beware of loops that never end
}

Integer tries = 0;
do {
    tries++;
} while (tries < 3);    // runs at least once

An infinite loop does not hang Salesforce for ever; the 10-second CPU limit will terminate it with a limit exception, but it wastes the transaction, so check your exit condition.

break and continue

break leaves the loop; continue skips to the next iteration:

Java
for (Integer value : values) {
    if (value == null) continue;      // skip empty
    if (value < 0) break;             // stop at first negative
    System.debug(value);
}

Stand-ins in Java

Java 21+ has a pattern-matching switch, which is close to switch on an SObject type. The stand-in below models a record-routing method with a sealed interface.

Java Stand-in (Java): switch on type and safe defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The next stand-in shows continue and break in a loop that totals valid amounts.

Java Stand-in (Java): continue and break

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Which loop should I use?

Situation Loop
Walk every item of a list or set for-each
Need a counter classic for
Process query results of unknown size SOQL for loop
Repeat until a condition changes while / do-while

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the ?. operator do?

    Safe navigation (?.) lets you read a member of an object that may be null without a NullPointerException.
  2. 2. Does an Apex switch statement fall through to the next when block?

    Only one when branch runs, so no break is needed.
  3. 3. What is the benefit of a SOQL for loop?

    The query still counts once, but the records are retrieved in batches, which saves heap space.
  4. 4. Which statement skips the rest of the current iteration?

    continue jumps to the next iteration; break leaves the loop entirely.

Summary

  • Conditions must be Boolean; && and || short-circuit, which makes null checks safe.
  • ?. and ?? reduce null-handling boilerplate.
  • switch on matches values and SObject types without fall-through.
  • Use for-each for collections and SOQL for loops for big query results.
  • break ends a loop, continue skips one iteration.

Next: SObjects and Fields in Apex