Control Structures in Apex: How to Use If-Else and Loops

May 11, 2025
514 Views
Control Structures in Apex: How to Use If-Else and Loops

Welcome to day 4 of the 10 day Apex series. When starting initially into Apex programming, We noticed that a strong and basic understanding of control structures is required to create efficient and useful code. In this blog, I will share some basic examples of using conditional statements and loops in Apex.

We will cover if-else statements, switch statements and the main types of loops which will include the break and continue statements as well. These code examples are aimed to be simple and easy to understand.

Simple Conditional Statements in Apex

Conditional statements will help us guide or advise our code based on whether certain conditions are met to perform specific actions. In Apex, we mostly work with if-else statements and switch statements.

If-Else Statements

let us execute one piece/block of code. if a condition is true and another if it is false, based on our business requirement or use case. Below is a very basic example to understand it:


public class TemperatureCheck {
    public static void checkTemperature(Integer temperature) {
        if (temperature > 25) {
            System.debug('It is warm outside.');
        } else {
            System.debug('It is cool outside.');
        }
    }
}

In this piece of code, if the temperature is above 25 degrees, it will log/execute that it is warm; otherwise, it will log that it is cool.

Switch Statements

Switch statements can make our code more clean and neat when we have multiple values to check against one variable based on our different business needs. Below is a simple example using user roles:


public class RoleMessage {
    public static void showRoleMessage(String role) {
        switch on role {
            when 'Admin' {
                System.debug('Welcome, Admin!');
            }
            when 'User' {
                System.debug('Hello, User!');
            }
            when else {
                System.debug('Role not recognized.');
            }
        }
    }
}

The above example displays a clear and straightforward method to handle different cases. The when else clause serves as a catch-all for any roles that don’t match the given cases then it will execute.

Also Read

Don’t forget to checkout: Apex Programming: Syntax, Data Types and Variables.

Easy-to-Follow Looping Structures

Loops are used when we need to repeat a section of code or perform actions for different conditions/cases. Apex supports several types of loops and below are their easiest examples.

For Loop

For loops are used when we know how many times we want to iterate for specific condition. Below is a very basic example that loops through numbers 1 to 5:


public class SimpleForLoop {
    public static void loopNumbers() {
        for (Integer i = 1; i <= 5; i++) {
            System.debug('Number: ' + i);
        }
    }
}

This for loop increments the variable i by 1 each time until it reaches 5, printing a number each time till conditions satisfy.

While Loop

While loops are useful when the number of iterations are not predetermined. Below is a basic example:


public class SimpleWhileLoop {
    public static void countDown() {
        Integer count = 5;
        while (count > 0) {
            System.debug('Count: ' + count);
            count--;  // Decrease count by 1
        }
        System.debug('Countdown complete!');
    }
}

This example counts down from 5 to 1, and then prints a final message when the loop ends.

Do-While Loop

The do-while loop executes the code block at least once before checking the condition. Below is a very basic example:


public class SimpleDoWhile {
    public static void runOnce() {
        Integer attempts = 0;
        do {
            System.debug('Attempt: ' + attempts);
            attempts++;
        } while (attempts < 1);
    }
}

Notice that even if the condition is false from the start, the code inside the do block will run once even if any of the condition is not matching.

Using Break and Continue for Better Control

Sometimes, we might need to exit a loop early or skip certain iterations that means no need to go through all iterations. Apex provides the break and continue statements for these executions based on our business requirements.

Break Statement

The break statement is used to exit a loop immediately when a condition is met. Below is a very basic example:


public class BreakExample {
    public static void findNumber() {
        for (Integer i = 1; i <= 10; i++) {
            if (i == 5) {
                System.debug('Found 5, exiting loop.');
                break;
            }
            System.debug('Number: ' + i);
        }
    }
}

In this code, when the number 5 is reached, the loop stops and no numbers after 5 are processed. Post condition is matched then it will just exit the iterations of the loop.

Continue Statement

The continue statement skips the current iteration and goes to the next loop iteration based on the conditions we place. Below is an easy-to-understand example:


public class ContinueExample {
    public static void skipOddNumbers() {
        for (Integer i = 1; i <= 10; i++) {
            if (i % 2 != 0) {
                continue;  // Skip the current iteration if the number is odd
            }
            System.debug('Even Number: ' + i);
        }
    }
}

With this example, only even numbers are printed because odd numbers are skipped, iteration works till i is 10.

Real-Life Use Cases

Using control structures well can help simplify our logic when processing data. Consider below the simple scenario that we want to process a list of numbers and handle each number differently based on its values.

The following code combines conditionals and loops in a easiest way that will help us to understand it properly:


public class ProcessNumbers {
    public static void processList() {
        List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};
        for (Integer num : numbers) {
            if (num % 2 == 0) {
                System.debug(num + ' is even.');
            } else {
                System.debug(num + ' is odd.');
            }
        }
    }
}

This code loops through a list of numbers and prints a message showing whether the number is even or odd. It is a clean and simple example that shows how we can combine a for loop with an if-else statement.

Tips for Writing Clean Control Structures

Here are few tips we can learn from above examples in Apex that can help us to write cleaner and more maintainable code:

  1. Keep Conditions Simple: Complex conditions can be broken into smaller parts or even separate helper methods. This improves readability. Also, will help us to debug in future if any issues arise.
  2. Choose the Right Loop: Use a for loop when we know the number of iterations and a while loop for conditions that depend on dynamic situations.
  3. Comments: While it is helpful to comment on our code, try to write self-explanatory statements. Comments should add clarity, not clutter.
  4. Test Complex Cases: Always test our loops and conditions with different inputs to ensure they behave as expected.

Conclusion

Control structures are the backbone of our code. Whether we are simply deciding which message to display or iterating over a list of values, mastering if-else statements, switch cases, and loops in Apex will go a long way in making our code both efficient and easy to understand. Start with these basic examples and as we grow more confident, we will naturally build up to more complex scenarios.

Today, we’re diving into Control Structures and Loops in Apex – the core elements that allow you to add logic and flow to your code.

Up next, on Day 5, we’ll explore SOQL and SOSL – Querying Data in Salesforce, where you’ll learn how to fetch records from the Salesforce database using efficient query languages.

Stay tuned and follow the Apex 10-Day Series. Happy coding!

Written by

user

Mohit Bansal

Salesforce Technical Architect | Lead | Salesforce Lightning & Integrations Expert | Pardot | 5X Salesforce Certified | App Publisher | Blogger

Contributor of the month
contributor
Gopinath G

Passionate about the intersection of cutting-edge technologies

Get the latest tips, news, updates, advice, inspiration, and more….

...
Boost Your Brand's Visibility

Want to promote your products/services in front of more customers?

...