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.

While Loops

The Apex while loop repeatedly executes a block of code as long as a particular Boolean condition remains true. Its syntax is:
1while (condition) {
2    code_block
3}

Curly braces ({}) are required around a code_block only if the block contains more than one statement.

Note

Unlike do-while, the while loop checks the Boolean condition statement before the first loop is executed. Consequently, it is possible for the code block to never execute.

As an example, the following code outputs the numbers 1 - 10 into the debug log:
1Integer count = 1;
2
3while (count < 11) {
4    System.debug(count);
5    count++;
6}