Chapter 5 - Logic Control and Looping Statements >

Logic Control and Looping Statements in Salesforce

# Logic Control and Looping Statements in Salesforce

← Hide

What You’ll Learn

What does logic control mean?

Types Of Logic Control

Explain Conditional, Switch and Looping statements with examples

## Logic Control And Looping Statement

To control the flow of code execution apex provides conditional statements and loops which help us execute the code based on conditions or execute the same code repeatedly for n number of times.

## Types Of Logic Control

In apex, logic control is divided into 3 parts:

1. Conditional Statements
2. Switch Statements
3. Looping Statements

### Conditional Statement

#### IF Statement

Use the if statement to specify a block of code to be executed if a condition is true.

Syntax:

if (condition)
{
// block of code to be executed if the condition is true
}

#### IF Else Statement

Use the else statement to specify a block of code to be executed if the condition is false.

Syntax:

if (condition)
{
// block of code to be executed if the condition is true
}
else
{
// block of code to be executed if the condition is false
}

#### IF Else If Statement

Use the else if statement to specify a new condition if the first condition is false.

Syntax:

if (condition1)
{
// block of code to be executed if condition1 is true
}
else if (condition2)
{
// block of code to be executed if condition1 is false and condition2 is true
}
else
{
// block of code to be executed if the condition1 is false and condition2 is false
}

#### Shorthand IF

If you have only one statement to execute, one for if, and one for else, you can put it all on the same line:

Syntax:

variable = (condition) ? expressionTrue : expressionFalse;

### Looping Statement

Loops can execute a block of code as long as a specified condition is reached.

#### While Loop

Syntax:

while (condition)
{
// code block to be executed
}

Example:

List<integer> iList = new List<integer>{2,4,6,3,5,8,5,3,5,8,8,5,9};
Integer i = 0;
while (i < iList.size())
{
i++;
// other statements to be executed
}

#### Do While Loop

Syntax:

do
{
// code block to be executed
} while (condition);

Example:

List<integer> iList = new List<integer>{2,4,6,3,5,8,5,3,5,8,8,5,9};
Integer i = 0;
do
{
i++;
// other statements to be executed
} while (i < iList.size());

#### For Loop

Syntax:

for(initialization ; condition ; increment/decrement/operation)
{
// code to be executed
}

Example:

List<integer> iList = new List<integer>{2,4,6,3,5,8,5,3,5,8,8,5,9};
for(Integer i=0; i < iList.size(); i++) {
// code block to be executed
}

#### ForEach Loop

Syntax:

for (type variable : arrayname)
{
// code block to be executed
}

Example:

List<integer> iList = new List<integer>{2,4,6,3,5,8,5,3,5,8,8,5,9};
for(Integer a: iList)
{
a = a*2;
}