This course is currently a work in progress. Please join the waitlist to receive regular updates.

Loops in apex

Loop is a block of code that executes repeatedly based on a specific condition or over elements in a collection. Loops are essential for developers when processing multiple records during program execution.

In apex, loops are commonly used to iterate through collections such as lists, sets or maps.

A practical use case for loops in apex is updating all contacts where the email field is blank and setting their email to noreply@company.com.

For loop syntax in Apex

Learn how the `for` loop works in Apex with an interactive step-by-step guide.

Syntax

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

Steps

  • 1Initialize: Set i = 0
  • 2Condition Check: Is i < 5?
  • 3Execute Block: Log value of i
  • 4Increment: Increase i by 1
  • 5Repeat: Go to Step 2

💡 Click on each step above to highlight the corresponding syntax.

In the above example:

  • The integer variable i is initialized with a value of 0.
  • The check i < 5 is performed next and continue the execution if that is true, otherwise exit from the loop.
  • If the loop continues its execution, the statements inside the loop will be executed. In the above case, the system.debug statements will be printed.
  • The next step is to update the value of i , which can be an increment or decrement operation. In our case, we selected an increment operation.
  • The next step is to evaluate the loop condition, which checks the value of i again and decides whether to execute the statements inside the loop. If the condition evaluates to true, the loop continues its execution; otherwise, it will exit the loop."