Salesforce Loops in Apex | The Developer Guide
Introduction
A loop is a programming structure that repeats a sequence of instructions again and again until a specific/desired condition is met.
In a loop structure, the loop checks the condition. If the condition requires action, it is executed. The same condition checks again and again until no further action is required. Each time the condition is checked is called an iteration.
Loop Control Statements
A statement that changes the execution of a loop from its designated sequence is known as a loop control statement. The following two-loop control statements are used in the apex.
Break
A break statement inside a loop terminates the loop immediately and executes the statements after the loop.
Continue
A continue statement skips the current iteration of the loop and executes with the next value in the loop.
Don't forget to check out: Using Batch Apex in Salesforce | The Developer Guide
Types of Loops in Salesforce
There are following three types of loops are used in the apex:
- For loop
- While loop
- Do While loop
1. For Loop
In apex for loop can be classified into three types:
-
Traditional For Loop
A for loop checks the condition first (at the top of the code) and executes the code block again and again until the condition is true.
Loop Syntax:
for (initial statement ; exit_condition; increment statement) { code_block }
For example, The following code will insert 200 accounts in Salesforce org having account names Test Account1, Test Account2, Test Account3.
for (integer a=0; a<200; a++) { Account acc = new account(); acc.name='Test Account'+a; Insert acc; }
-
The list or set iteration for loop
This type of for loop iterates over a list or set of primitive data type/sObject.
Loop Syntax:
for (variable : list or set) { Code block... }
-
The SOQL for loop
This type of for loop iterates over a list of sObject which are retrieved from SOQL.
Loop Syntax:
for (variable : [soql query]) { Code block... }
2. While Loop
Repeats a statement or group of instructions while a given boolean condition is true. It checks the condition before executing the loop body/code block.
Loop Syntax:
while (condition) { Code block... }
Check out another amazing blog by Arun here: Transaction Security in Salesforce
3. Do-While Loop
In for and while loops, the loop checks the condition at the top of the loop, but in the do-while loop checks its condition at the bottom of the loop. A do-while loop is similar to a while loop, the only difference is that it is guaranteed to execute at least one time.
Loop Syntax:
do { Code block... } while (condition);
For Example:
Integer a=10; do { Account acc= new account(); acc.name='Test Account'+a; Insert acc; } while (a>15);
In the above code example, the condition is checked at the bottom and it is not true still the loop will insert an account in the Salesforce org. Because the do-while executes at least once without checking the condition.
Responses