Apex · Salesforce

APEX – LOOPS

Loops are used when a particular piece of code should be repeated with the desired number of iteration. Apex supports the standard traditional for loop as well as other advanced types of Loops. In this chapter, we will discuss in detail about the Loops in Apex.

A loop statement allows us to execute a statement or group of statements multiple times and following is the general from of a loop statement in most of the programming languages −

The following tables lists down the different Loops that handle looping requirements in Apex Programming language. Click the following links to check their detail.

Types of Loops:-

  • For Loop
  • While Loop
  • Do-While Loop

For Loop:-

for loop is a repetition control structure that allows you to efficiently write a loop that needs to execute a specific number of times. Consider a business case wherein, we are required to process or update the 100 records in one time. This is where the Loop syntax helps and makes work easier.

Syntax:-

                   for (variable : list_or_set) { code_block }

               This type of for loop is used when we do not want to create the List and directly iterate over the returned set of records of the SOQL query. We will study more about the SOQL query in subsequent chapters. For now, just remember that it returns the list of records and field as given in the query.

Syntax:-

                   for (variable : [soql_query]) { code_block }

One thing to note here is that the variable_list or variable should always be of the same type as the records returned by the Query. In our example, it is of the same type as APEX_Invoice_c.

While Loop:-

             A while loop statement in Apex programming language repeatedly executes a target statement as long as a given condition is true. This is in a way similar to the do-while loop, with one major difference. It will execute the code block only when the condition is true, but in the do-while loop, even if the condition is false, it will execute the code block at least once.

Syntax:-

                  while (Boolean_condition) { execute_code_block }

Do-While Loop:-

           Unlike the for and the while loops which test the loop condition at the top of the loop, the do…while loop checks its condition at the bottom of the loop.

A do…while loop is similar to a while loop, except that a do…while loop is guaranteed to execute at least one time.

Syntax:-

                 do { code_to_execute } while (Boolean_condition);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s