Apex - While Loop

A while loop statement in Apex programming language repeatedly executes a target statement as long as a given condition is true. This is in a way similar to the do-while loop, with one major difference. It will execute the code block only when the condition is true, but in the do-while loop, even if the condition is false, it will execute the code block at least once.


while (Boolean_condition) { execute_code_block }

Flow Diagram

Apex Wile Loop

Here key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.


In this example, we will implement the same scenario that we did for the do-while loop, but this time using the While Loop. It will update the description for 10 records.

//Fetch 20 records from database
List<apex_invoice_c> InvoiceList = [SELECT Id, APEX_Description_c,
   APEX_Status_c FROM APEX_Invoice_c LIMIT 20];
Integer i = 1;

//Update ONLY 10 records
while (i< 10) {
   InvoiceList[i].APEX_Description__c = 'This is the '+i+'Invoice';
   System.debug('Updated Description'+InvoiceList[i].APEX_Description_c);
Kickstart Your Career

Get certified by completing the course

Get Started