How to use loop in apex Salesforce

In Apex, you can use loops to iterate over collections, execute a block of code multiple times, or perform repetitive tasks. There are mainly three types of loops in Apex: for loop, while loop, and do-while loop. Here are examples of each:

if you want to how to create apex class click here or salesforce guide

1- For Loop:

The for loop is commonly used when the number of iterations is known.


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

				

This loop will iterate from 1 to 5, and the System.debug statement will display each iteration.

2- While Loop:

The while loop is useful when the number of iterations is not known beforehand.


					Integer j = 1;
while (j <= 5) {
    System.debug('Iteration ' + j);
    j++;
}

				

This loop will also iterate from 1 to 5, and the System.debug statement will be executed in each iteration.

3- Do-While Loop:

Similar to the while loop, the do-while loop is used when you want to execute the loop body at least once, regardless of the loop condition.


					Integer k = 1;
do {
    System.debug('Iteration ' + k);
    k++;
} while (k <= 5);

				

This loop will iterate from 1 to 5, and the System.debug statement will be executed at least once.

Looping Through Lists:

You can also use loops to iterate through collections like lists or arrays.


					List fruits = new List{'Apple', 'Orange', 'Banana'};
for (String fruit : fruits) {
    System.debug('Fruit: ' + fruit);
}

				

This loop iterates through each element in the fruits list and prints each fruit.

Thank,s..

Raghvendra Pratap Singh
Raghvendra Pratap Singh  Apex Developer

Scroll to Top