Apex - do-while Loop



Unlike the for and the while loops which test the loop condition at the top of the loop, the do...while loop checks its condition at the bottom of the loop.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at least one time.

Syntax

do { code_to_execute } while (Boolean_condition);

Flow Diagram

Apex do-while Loop

Example

For our Chemical Company, we will be updating the only first 1 record in List, not more than that.

// Code for do while loop
List<apex_invoice__c> InvoiceList = [SELECT Id, APEX_Description__c,
   APEX_Status__c FROM APEX_Invoice__c LIMIT 20];  //it will fetch only 20 records

Integer i = 0;
do {
   InvoiceList[i].APEX_Description__c = 'This is the '+i+' Invoice';
   
   // This will print the updated description in debug log
   System.debug('****Updated Description'+InvoiceList[i].APEX_Description__c);
   i++; // Increment the counter
} while (i< 1);   // iterate till 1st record only
apex_loops.htm
Advertisements