Skip to main content

Apex Control Statements

Apex, Salesforce’s programming language, includes several control statements to control the flow of logic in your code. These include: if / else switch for loops while / do-while loops Let’s go through each with clear syntax, examples, and explanation.

1. if, else if, else Statement

The if statement executes a block of code only if a specified condition is true.

Syntax:

        if (condition) {
            // code if condition is true
        } else if (otherCondition) {
            // code if otherCondition is true
        } else {
            // code if none are true
        }
        
        
Example:

        Integer score = 75;
        if (score >= 90) {
            System.debug('Grade A');
        } else if (score >= 75) {
            System.debug('Grade B');
        } else {
            System.debug('Grade C');
        }
        
Output:

        Grade B
        

2. switch Statement (Available in Apex from v50.0+)

The switch statement is useful when comparing a single variable to multiple values.

Syntax:

        switch on variable {
            when value1 {
                // Code for value1
            }
            when value2 {
                // Code for value2
            }
            when else {
                // Default case
            }
        }        
        
Example:

        String status = 'Closed';
        switch on status {
            when 'Open' {
                System.debug('Case is open');
            }
            when 'Closed' {
                System.debug('Case is closed');
            }
            when else {
                System.debug('Unknown status');
            }
        }           
        
Output:

        Case is closed        
        

3. for Loop (Traditional & Enhanced)

Used to iterate over a block of code multiple times.

A. Traditional For Loop

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

i = 0
i = 1
i = 2
i = 3
i = 4             
        
B. For-Each Loop (Enhanced)

Useful for looping through collections like lists or sets.


        List fruits = new List{'Apple', 'Banana', 'Cherry'};
            for (String fruit : fruits) {
                System.debug('Fruit: ' + fruit);
            }
        

4. while and do-while Loops

A. while Loop

Executes a block as long as a condition is true.


Integer x = 0;
while (x < 3) {
    System.debug('x = ' + x);
    x++;
}
        
B. do-while Loop

Executes at least once, then checks condition.


Integer y = 0;
do {
    System.debug('y = ' + y);
    y++;
} while (y < 3);

        

Summary Table

Statement Use Case
if/else Run different blocks based on a condition
switch Choose among many constant values
for Loop a fixed number of times
while Loop while a condition is true
do-while Loop at least once