Loops in Apex

Loops in Apex are used to execute a piece of code multiple times. There are five types of loops in Apex:

  • do…while
  • while
  • The standard for loop
  • The for each loop
  • The for loop for SOQL

The first two are never used in the real world and doing so goes against the best practices, so we won’t discuss them. We won’t get into the for loop for SOQL until the SOQL article either, which leaves only the standard for loop!

Standard “for” loop

The standard for loop in Apex is used to run a block of code a defined number of times. The syntax for the standard for loop is as follows:

for(initialization; testCondition; updateExpression) {
  // loop body
}
  1. initialization: Declares and initializes a variable. Executes only once.
  2. testCondition: Evaluated on each execution. If it evaluates to true, the code in the loop is executed. If it evaluates to false, the code isn’t executed and the first line after the for loop is executed.
  3. updateExpression: Executed after each run. Usually, it’s the update of the variable defined in the initialization block.
  4. Loop body: Code that needs to be repeated.

Here’s the flowchart of a loop execution:

 

Loops in Apex
Loops in Apex

Example #1 – Print String five times

for(Integer i = 0; i < 5; i++) {
    System.debug('Wow, Apex is cool!');
}

Here:

  • Integer i = 0: Declaration of a loop variable called i with the Integer type.
  • i < 5: If this condition is true, the loop body will be executed.
  • i++: Update expression that will be executed every time the loop body is executed.
  • System.debug(‘Wow, Apex is cool!’);: Loop body.

Output

Wow, Apex is cool!
Wow, Apex is cool!
Wow, Apex is cool!
Wow, Apex is cool!
Wow, Apex is cool!
untitled 1 1

Execution

image 7

Example #2 – Print numbers from 1 to n

Note that this time, we start with 1 and stop at 5:

Integer n = 5;
for(Integer i = 1; i <= n; i++) {
    System.debug(i);
}

Output

1
2
3
4
5
untitled 2 1

Execution

image 8

Example #3 – Sum between n and m

Integer n = 5;
Integer m = 100;
Integer sum = 0;

for(Integer i = n; i <= m; i++) {
    sum = sum + i;
}

System.debug(sum);

Output

5040

Execution

image 9

Lists and loops

Let’s say you want to add 50 new entries to a list of names.

List<String> names = new List<String>();

for(Integer i = 0; i < 50; i++) {
    String name = 'Name ' + i; // Include index into the name
    names.add(name); // add name variable into the list
}

This way, we’ll put 50 names in the list. We added i to each name so we can at least identify them and not have 50 identical names. There isn’t enough space to show all 50 elements, but here’s how it looks for the first six:

still basics of apex advanced 11 1

Example #4 – Add 50 new contacts

You can use lists with any data type—even standard objects such as contacts. Keep in mind that these contacts haven’t been inserted into the system yet.

List<Contact> contacts = new List<Contact>();

for(Integer i = 0; i < 50; i++) {
    Contact contact = new Contact();
    contact.LastName = 'Name ' + i; 
    contacts.add(contact); 
}

System.debug(contacts);

Output

(Contact:{LastName=Name 0}, Contact:{LastName=Name 1}, ...)

 

untitled 3 1

“For each” loop

The most common task that you’ll face as a developer is iterating through a list of objects. There’s a special type of loop for this case called for-each because you go through each element in the list. Here’s the syntax:

for(DataType variableName : collection) {
    // loop body
}
  • DataType: Data type of the elements in the collection.
  • variableName: Each item from the list is assigned to this variable.
  • collection: Can be a list or set.
  • Loop body: Peace of code that will be repeated for each element.

The loop variable will take the value of the first element in the first iteration, the value of the second element in the second element, the value of the third element… And the loop body will be executed as many times as there are elements in the list.

Example #5 – Iterate through every name

List<String> names = new List<String>();
names.add('Alex'); 
names.add('John'); 
names.add('Oliver');

for(String name : names) {
        System.debug(name);
}

Output

Alex
John
Oliver

Execution

  • In the first iteration, name will be equal to Alex.
  • In the second iteration, name will be equal to John.
  • In the third iteration, name will be equal to Oliver.

Example #6 – Sum of all integers in the list

List<Integer> numbers = new List<Integer>{1, -10, 5, 0, 33, -13, 2};

Integer sum = 0;
for(Integer numberVariable : numbers) {
        sum = sum + numberVariable; // Add number to the sum
}

System.debug(sum); // output the sum = 18

Output

18
image 10

“For each” vs. standard “for” loop

The code here is the same as the code from Example #6 and will produce the same output, but it’s much more difficult to understand.

List<String> names = new List<String>();
names.add('Alex'); 
names.add('John'); 
names.add('Oliver');

for(Integer i = 0; i < names.size(); i++) {
        String name = names.get(i);
        System.debug(name);
}

You should always use a for-each loop instead of a standard for loop if you can. The only case where you can’t is when you need to work with the indexes of elements.

Nested loops

We can have loops inside of loops too! This is a difficult topic, and you’ll use this concept a lot as a developer. Thankfully, it’s not super important for beginners to understand it. As if simple loops weren’t complicated enough :).

for(Integer i = 0; i < 3; i++) {
    System.debug('i = ' + i);
    for(Integer j = 0; j < 3; j++) {
        System.debug('j = ' + j);
    }
}

Output

i = 0
    j = 0
    j = 1
    j = 2
i = 1
    j = 0
    j = 1
    j = 2
i = 2
    j = 0
    j = 1
    j = 2

Execution

image 11

Break

Sometimes, we want to skip the execution of the whole loop if a certain condition is true. We can use the break statement for that. The break statement terminates the loop and Apex continues the execution on the first line after the loop.

still basics of apex advanced 13 1 1

Example #7 – Stop at a certain name

List<String> names = new List<String>();
names.add('Alex'); 
names.add('John'); 
names.add('Oliver');
names.add('Emma');

for(String name : names) {
    if(name == 'Oliver') {
        break;
    }
    System.debug(name);
}

Output

Alex
John

As soon as Apex determines that the name will be Oliver, it’ll go inside the if statement and stop the loop’s execution.

Example #8 – Stop after a number

for(Integer i = 0; i < 100; i++) {
    if(i == 5) {
        break;
    }
    System.debug(i);
}

Output

0
1
2
3
4

As soon as i == 5 evaluates to true, the loop will terminate and no debug log will be executed.

It’s important to note that the break statement only stops a current loop. If you have nested loops, break will stop the one loop where it was executed.

 

still basics of apex advanced 14 1

Continue

The continue statement skips the current iteration and goes back to the loop’s definition.

Example #9 – Calculate only positive numbers

List<Integer> numbers = new List<Integer>{1, -10, 5, 0, 33, -13, 2};

Integer sum = 0;
for(Integer numberVariable : numbers) {
    if(numberVariable <= 0) {
        continue;
    }
    sum += numberVariable;
}

System.debug(sum);

Output

41

Execution

image 12

Just as with the break statement, continue only works for going back to the current loop’s definition.

That’s it?

No, but we’re slowly getting there! We still need to discuss loops with SOQL, which we’ll cover in the next article. There isn’t much theory behind loops, but without practice, you won’t be able to understand them. So go ahead and solve some tasks in the Apex Sandbox!

<h4 class="item-title">admin</h4>

admin

Related Posts

blog images 12

SOQL in Apex

blog images 10

Lists in Apex

blog images 9

If/Else in Apex

Leave a Reply

Your email address will not be published. Required fields are marked *

t.me/ihor_igor

Subscribe for news about new courses or discounts.

No spam, we promise.


    © 2023 All Rights Reserved by site  igor@cloud-prism.com