Salesforce Apex Tutorial – Chapter 10: Loops in Apex

Salesforce Apex Tutorial – Chapter 10: Loops in Apex

On October 25, 2021, Posted by , In Salesforce Apex Tutorial, With Comments Off on Salesforce Apex Tutorial – Chapter 10: Loops in Apex
Loops-in-Apex

A loop is a block of code that is repeated until a specified condition is met. Salesforce apex supports both traditional and advanced loop types. Using a loop statement, we can execute a statement or group of statements multiple times.

Below is the flow diagram of a loop followed by most programming languages.

  1. do {statement} while (Boolean_condition);

In an Apex do-while loop, code is executed until a certain Boolean condition is met.

Syntax:

do {
code_block
}
while (condition);

2. while (Boolean_condition) statement;

A while loop in Apex executes a block of code repeatedly until a particular Boolean condition is satisfied.

Syntax:

while (condition) {
code_block
}

3. for (initialization; Boolean_exit_condition; increment) statement;

Apex provides three variants of for loop:

  • The Standard for loop

Syntax:

for (init_stmt; exit_condition; increment_stmt) {
code_block
}
  • The list or set iteration for loop:

Syntax:

for (variable : list_or_set) {
code_block
}

The SOQL for loop:

Syntax:

for (variable : [soql_query]) {
code_block
}

4. for (variable : array_or_set) statement;

In a list or set loop, the elements in a list or set are iterated over.

Syntax:

for (variable : list_or_set) {
code_block
}

5. for (variable : [inline_soql_query]) statement;

The SOQL for loop iterates over all the sObject records that the SOQL query returns.

Syntax:

for (variable : [soql_query]) {
code_block
}
Comments are closed.