Logic Control

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

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 

while (condition)

{

   // code block to be executed

}

Do While Loop

Syntax:

do 

{

  // code block to be executed

}while (condition);

For Loop

Syntax:

for(initialization ; condition ; increment/decrement/operation)

{

}

Example:

List<integer> iList = new List<integer>{2,4,6,3,5,8,5,3,5,8,8,5,9};

for(integer a: iList)

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;

}

Our Recent Blog

Share This Post