Table of Contents
Loop control structures in Salesforce Apex
Loop Control structures in Salesforce Apex are very important in controlling the loops. When you have any specific condition to apply on the loops, this loop control structure comes very handy in implementing those conditions. There are two types of loop control structures in Apex which are similar to Java. In this article we will explore more about it.
Type of Loop control structures
There are two types of loop control structures, they are “Break” and “Continue”. Let’s discuss them now.
1. Break
The break keyword is used to end the loop when any condition is met. Normally we write the Break keyword inside an “If” condition and it gets executed if the condition is true and breaks the loop. Let’s see an example.
Example:
public class textBreak { public static void testing(){ Integer i = 0; for(i=0; i<10; i++) { if(i==5) { break; } System.debug(i); } } }
Output:
Explanation:
Here, in the code, we wrote a loop for Printing numbers from 0 to 9. But also we have a break keyword inside an “if” condition to execute the break statement if the value of the variable is 5. Hence, the loop ended without printing the other statements.
2. Continue
When it comes to Continue Keyword, It just makes the current iteration end and continues with the following iterations. That means the Continue statement executes the current ongoing loop breaks but then continues again with its following iterations unlike in Break Statement. Let’s see an example to understate the difference between the both.
Example:
public class demo { public static void breakAndContinue(){ Integer i = 0; for(i=0; i<10; i++) { if(i==5) { continue; } System.debug(i); } } }
Output:
Explanation:
Here, we just replaced the break keyword with the continue keyword and you may notice the difference. In the break, the loop got ended. But in continue, it ended only the current iteration. As you can see the following numbers got printed in the execution log.
0 Comments