Loops in Apex: A Beginner’s Guide

Loops are an essential part of programming, allowing you to repeat actions without writing the same code multiple times. In Salesforce’s Apex, loops help developers process data efficiently, making their code more concise and manageable.

In this article, we will introduce looping/iteration in Apex and explain its various types, making it easy for new students to understand how loops work.

What is a Loop in Programming?

A loop is a control structure that allows you to execute a block of code repeatedly as long as a specific condition is true. Instead of manually writing the same code multiple times, a loop will automatically repeat the actions until the condition is no longer met.

Benefits of Loops:

  • Efficiency: You can process large datasets or execute repetitive tasks quickly.
  • Readability: Loops reduce the need for writing repetitive code, making your program easier to read and maintain.
  • Flexibility: Loops can adapt to changing data, making them suitable for scenarios where you don’t know how many iterations are needed beforehand.

Types of Loops in Apex

Apex supports several types of loops that handle different scenarios depending on how and when you want the loop to execute.

1. For Loop – The for loop is commonly used when you know the number of iterations you want to perform. You specify a starting point, an ending condition, and a way to increment or decrement the loop counter.
Example: Loop through numbers 1 to 5.

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

In this example, the loop starts at i = 1 and increments i by 1 in each iteration. The loop runs as long as i is less than or equal to 5.

2. While Loop – The while loop keeps running as long as the condition is true. This loop is best used when you don’t know beforehand how many times the loop should run but know the condition that should keep it going.
Example: Print numbers from 1 to 5 using a while loop.

while (i <= 5)
{
System.debug(i);
i++;
}

In this example, the loop continues as long as i is less than or equal to 5. After each iteration, i is incremented.

3. Do-While Loop – The do-while loop is similar to the while loop, but the condition is checked after the code has executed, ensuring that the loop runs at least once.

Example: Print numbers from 1 to 5 using a do-while loop.

Integer i = 1;
do
{
System.debug(i);
i++;
} while (i <= 5);

In this case, even if i starts greater than 5, the loop will run once before the condition is checked.

4. For-Each Loop – The for-each loop is used to iterate through collections, such as lists or sets, without needing to know the number of elements. It processes each item in the collection one by one. We are going to cover the collections in next chapter.

Example: Loop through a list of names.

List<String> names = new List<String>{'John', 'Jane', 'Alice'};
for (String name : names)
{
System.debug(name);
}

Here, the loop goes through each element in the list names and prints it.

    Using Break and Continue Statements

    Loops in Apex also support the break and continue statements to control how the loop behaves.

    Break Statement – The break statement immediately exits the loop, stopping further iterations, even if the condition is still true.
    Example: Stop the loop when i reaches 3.

    for (Integer i = 1; i <= 5; i++)
    {
    if (i == 3)
    {
    break;
    }
    System.debug(i);
    }

    In this example, the loop will stop when i equals 3, and only 1 and 2 will be printed.

    Continue Statement – The continue statement skips the current iteration and moves to the next one without exiting the loop entirely.

    Example: Skip printing the number 3.

    for (Integer i = 1; i <= 5; i++)
    {
    if (i == 3)
    {
    continue;
    }
    System.debug(i);
    }

    In this case, the loop skips printing the number 3 but continues printing the other numbers.

    Nested Loops

    Nested loops are loops inside other loops. These are useful when you need to perform operations that require multiple levels of repetition. For example, processing rows and columns in a table or iterating over a list of lists.

    Example: Print a 3×3 grid of numbers using nested loops.

    for (Integer row = 1; row <= 3; row++)
    {
    for (Integer col = 1; col <= 3; col++)
    {
    System.debug('Row ' + row + ', Column ' + col);
    }
    }

    In this example, the outer loop runs three times (for each row), and the inner loop also runs three times (for each column). As a result, the total number of iterations will be 9.

    Practice Problems

    1. Problem 1: Write a loop that prints all the even numbers from 1 to 10.
    2. Problem 2: Create a for loop that iterates through a list of numbers and prints only the numbers greater than 5.
    3. Problem 3: Use a while loop to sum the numbers from 1 to 100.
    4. Problem 4: Use a for-each loop to iterate through a list of strings and print each string that contains more than 3 characters.

      Conclusion

      Understanding loops is essential for efficient and effective programming in Apex. Whether you’re processing data or automating repetitive tasks, loops allow you to repeat actions without redundant code. By mastering different types of loops—such as for, while, do-while, and for-each loops—you can handle a wide range of programming scenarios. Additionally, the break and continue statements give you more control over how and when loops execute.

      Practice using loops in your Apex programs, and soon you’ll be able to write more powerful and dynamic Salesforce applications!