,

For Loops

Apex support three types of For loops: traditional, list/set iteration, and SOQL.

The traditional For loop uses the following syntax:

for (init_statement; exit_condition; increment_statement) {
 code_block;
 }

The init_statement executes when the loop is first entered and can initialize more than one variable. The exit_condition is evaluated every time the loop executes. If the condition evaluates to false, the loop ends. If the condition evaluates to true, the code_block executes, followed by the increment statement.

A typical For loop of this variety is as follows:

for (Integer I = 0; I < 10 ; I++) {
 System.debug('Iteration ' + I);
 }

This loop prints a list to the debug console consisting of the word Iteration followed by the values of I, from 0 to 9.

Apex also supports For loops that are based on the entries in a set or a list. The syntax is as follows:

for (variable : list_or_set) {
 code_block;
 }

This For loop executes once for each entry in the initial list or set variable. This variable must be the same data type as the list or set. You can use this syntax to get the same results as the previous For loop with the following code:

Integer[] listInts = new Integer[]{0,1,2,3,4,5,6,7,8,9};
for (Integer i : listInts) {
 System.debug('Iteration ' + i);
 }

Apex code also supports a very powerful For loop that is used in association with SOQL statements to iterate through a set of results. This loop syntax is especially powerful since you can use it to circumvent limitations on the number of entries in a collection. You will learn all about this type of For loop in the next chapter, which focuses on using Apex with data sets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.18.253