Note: This release is in preview. Features described here don’t become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.

Traditional For Loops

The traditional for loop in Apex corresponds to the traditional syntax used in Java and other languages. Its syntax is:
1for (init_stmt; exit_condition; increment_stmt) {
2    code_block
3}
When executing this type of for loop, the Apex runtime engine performs the following steps, in order:
  1. Execute the init_stmt component of the loop. Note that multiple variables can be declared and/or initialized in this statement, separated by commas.
  2. Perform the exit_condition check. If true, the loop continues. If false, the loop exits.
  3. Execute the code_block.
  4. Execute the increment_stmt statement.
  5. Return to Step 2.
As an example, the following code outputs the numbers 1 - 10 into the debug log. Note that an additional initialization variable, j, is included to demonstrate the syntax:
1for (Integer i = 0, j = 0; i < 10; i++) {
2    System.debug(i+1);
3}