5.4 Break and Continue

The concept

Sometimes, we don’t need to execute the whole loop. Just need run part of the loop and when certain things happen, we can break the loop. For example, when we want to search for a certain value in an array. In some other scenarios, we might want to quit our current single loop run but don’t want to abandon the whole loop. In those cases, we need to use keyword break and continue. Below is the sample code:


List<String> seasons = new List<String>{'Winter', 'Spring', 'Summer', 'Fall'};
Integer index = -1; //if not found, the index is -1

for(Integer i = 0; i < seasons.size(); i++) 
{
    if(seasons[i] == 'Spring') 
    {
        index = i;
        break;
    }
}
System.debug('The index of Spring is: ' + index);

//Calculate the sum of all the numbers below 20 if it is not multiples of 3
Integer sum = 0;
for(Integer i = 1; i <= 20; i++)
{
    if(Math.mod(i, 3) == 0) 
    {
        continue;
    }
    sum += i;
}

System.debug('The sum is: ' + sum);

The result:
breakandcontinue2

A bit explanation

As we have explained before. break is quitting the whole loop while continue is quitting the current run. You will find those two keywords getting more useful after your programme getting a little bit more complicated.

Exercise

Think about how do you write today’s code without¬†using the keywords break and continue.

Next Post

6.1 Calculate multiples of 3

Subscribe to Sfdcinpractice

Subscribe to get the latest blogs and tutorials of sfdcinpractice. No spam, no trash, only the awesome posts from sfdcinpractice. 

Leave a Reply

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