Loops in Salesforce Apex

Introduction

Loops in Salesforce Apex works exactly the same as loops in any other language. These are very important in any programming language and we use them more often. Let us learn more about loops with suitable examples here.

Loops in Salesforce Apex

As said loops are the same everywhere, simply loops are the execution of certain code several times until the specified condition meets false. Hence as long as the condition evaluates to be true the loop repeats. In Salesforce we have 5 types we can write these loops and let’s see them here.

Types of loops in Salesforce Apex

do {statement} while (Boolean_condition);

well, this is a different one from others as it checks the condition after the execution. This kind of loop is used when you want to execute the statement at least once irrespective of the condition. Let’s look at a simple flow diagram now.

Flow Diagram:

Do while loop in Salesforce


Syntax:

do{
      Statement;
}while( Condition );

 

Example:

public class loops {
    public static void doWhileExampel(){
        integer i = 0;
                    do {
                           i++;
                          System.debug('The num is => ' + i);
                    } while (i<= 5);
    }
}

 

Output:

check the output to understand it better.

Output of Do while loop in Salesforce

 

while (Boolean_conditionstatement;

While the statement is the simple one and most used, simply it checks the condition before execution of the code and only if the conditions evaluate to be true the code gets executed.

Flow Diagram:

while loop in Salesforce

 

Syntax:

While( Condition ){
Statement;
}

Example:

                public class demoClass {
                                   public static void whileExampel(){
                                          Integer i = 0;
                                          While (i < 5) {
                                                  System.debug('The num is => ' + i);
                                                  i++;
                                          }
                             }
              }

Output:

Output of while loop in Salesforce
 

for (initializationBoolean_exit_conditionincrementstatement;

For loops works the same as the above but it has a better syntax. Simply it has a counter which goes through the condition if true and gets updated. When the condition evaluates to false it then exits the loop. Better let’s understand it with a flow diagram, syntax and an example.

Flow Diagram:

For loop in Salesforce


Syntax:
 

For( Initialization ; Condition; Updation ) {
                Statement;
}

 

Example:

public class loop {
   
    public static void forExampel(){
                
        for(integer i=0; i<5; i++){
            System.debug('The num is => ' + i);
        }
    }
}

 

Output:

Output of For loop in Salesforce

 

for (Datatype variable : array_or_setstatement;

This is some advanced for loop for the above one, here, we just have an array or set and every element inside is iterated till the end. Simply we consider a variable to store that element. Let’s see the syntax.

Syntax:

For( Datatype Variable : List ) {
                Condition;
                }

 

Example:

public class loops{
   
    public static void forExample2(){
       
        Set<Integer> nums = new Set<Integer>();
        nums.add(1);
        nums.add(2);
        nums.add(3);
        nums.add(4);
       
        for(Integer i : nums){
            System.debug('The num is => ' + i);
        }
    }
}

 

Output:

 

 

for (Datatype variable : [inline_soql_query]) statement;

This can be said as more advanced as we don’t even store the results in any variable, we simply iterate through the results from the query itself, pretty simple ah, Yeah. Let’s see the syntax and an example then.

Syntax:

For(  Datatype variable : [ inline soql query] ){
                Statement;
                }

 

Example:

public class loops{
   
    public static void forExampel3(){
       
        for(Account acc : [SELECT Name, id FROM Account Limit 5]){
            System.debug('The Account name is => ' + acc);
        }
    }
}

 

Output:  

Output of Advanced For loop in Salesforce 2

 

Reference

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_loops.htm

https://trailhead.salesforce.com/content/learn/modules/object-oriented-programming-for-admins/use-a-for-loop-to-iterate-through-a-list#:~:text=As%20you%20learned%20in%20Apex,has%20three%20types%20of%20loops.

https://www.sfdc99.com/2013/10/06/loops-for-and-foreach-loops/

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.