Loops in Apex

Looping is a feature that makes the execution of a set of functions multiple times, although some condition evaluates to true.

There are 3 types of loops:

  • While loop
  • For loop
  • Do-while loop

While loop:

A while loop is a control flow statement that allows code to be executed many times based on a given boolean condition. The while loop can be thought as a repeating if statement.

 Syntax:

  • If the Boolean condition is true, then the loop statement will get executed, and if the boolean condition is false, then the control will come out outside of the loop.
Salesforce Loops in Apex

Example1:

 Output:

Salesforce Loops in Apex

In the above example, we have created a variable called (i) and initialized the value of the variable to 1, then, it checks while 1 is less than or equals to 10(condition is true). Now it will display “Javatpoint” on the screen. The increment operator (i++) will increase the value of (i) by 1.

Example2:

Output:

Salesforce Loops in Apex

Example3:

Output:

Salesforce Loops in Apex

Example4:

Output:

Salesforce Loops in Apex

Example5:

Output:

Salesforce Loops in Apex

For loop:

A for loop statement consumes the initialization, condition, and increment/decrement in one line by providing a shorter, easy to debug structure of looping.

Syntax:

Salesforce Loops in Apex

The initialization will only get executed once.

The condition and increment/decrement will be executed again.

Once it initialized, it will check for the condition, if the condition is true, then the statement will get executed, and again it will increment/decrement.

Once it increment/decrement, then again we check for the condition, if the condition is still true, it will get executed.

Once the condition becomes false, then the loop will stop further execution.

Example7:

Output:

Salesforce Loops in Apex

Example8:

Output:

Salesforce Loops in Apex

Example9: Even no. in reverse order.

Output:

Salesforce Loops in Apex

Three different types of for loop in Apex:

  • Traditional for loop

        Syntax:

  • Set iteration for loop

Syntax:

  • SOQL for loop

Syntax:

Example10:

Output:

Salesforce Loops in Apex

Example11:

Output:

Salesforce Loops in Apex

Break and Continue Statement:

Break statement: The break statement is used to jump out of a loop.

Continue statement:  The continue statement breaks one iteration in the loop (it will just skip the particular statement).

Example12:

Output:

Salesforce Loops in Apex

In the above example, the break statement will come out of the loop once it hit the value 5.

Example13:

Output:

Salesforce Loops in Apex

In the above example, the continue statement skips the iteration (10) and jump to the next iteration.

Nested Loop:

 Placing a loop inside another loop is called a nested loop.

Example14:

Output:

Salesforce Loops in Apex

Example15:

Output:

Salesforce Loops in Apex

Pin It on Pinterest

Share This