In Apex, the keyword and statement break
enables developers to take control over a loop's flow.
The break statement can terminate a loop's iteration sequence immediately. For instance, the following for loop would be pointless:
for(Integer num : numbers){ break; // nothing below would ever run }
Typically, we use the break
statement conditionally. Suppose you have to sum up every integer in a list until you encounter an index containing the element 0
. If it does, the loop should exit immediately. Otherwise all elements should be summed:
Integer[] numbersToSum = new Integer[] {5, 10, 2, 0, 3, 6}; Integer sumOfIntegers = calculateSum(numbersToSum); // sumOfIntegers will be 17 public Integer calculateSum(Integer[] numbers){ Integer sum = 0; for(Integer i = 0; i < numbers.size(); i++){ if(numbers[i] == 0){ break; } sum += numbers[i]; } return sum; }
In this example, the loop will iterate through the list, and if the current index contains a 0
, the loop will terminate immediately, and the next line that will be executed is return sum;
. If the list does not contain a 0
element, all the indexes will be accessed, and their values summed.