In this tutorial, I will explain logical and looping statements in Salesforce Apex Programming. We will explore the logical and looping statements available in Salesforce Apex and learn how to declare and utilize them to implement complex business logic, automate processes, and handle bulk operations.
Logical Statements in Salesforce Apex
In Salesforce Apex, a logical statement is used to make decisions during code execution by evaluating conditions and executing code blocks based on whether the conditions are true or false. Logical statements control the program’s flow and enable you to implement business logic effectively.
Types of Logical Statements in Salesforce Apex
Logic control in Salesforce Apex includes conditional statements that help manage execution flow based on specific conditions. The following are the primary types of logic controls:
- If Statement
- If-Else Statement
- Else-If Statement / Nested If-Else Statement
- Switch Statement
In the following steps, I will explain these logical statements using examples.
1. If Statement in Salesforce Apex
The if conditions in Apex are similar to those in other programming languages. The if statement evaluates a condition and executes a block of code if the condition is true.
Syntax:
if ( Condition ){
//logic;
}For example, we want to develop Apex code to display the number of records for any particular user with an opportunity stage name of ‘closed won’.
Here, I created a list to store opportunity records. Now, using the if condition, we will check whether there is any record available on the list. If a record is available, then execute the if block, which returns the record count.
public class Demo {
public void IfConditionDemo() {
Id ownerId = '0055i000004xf7XAAQ';
List<Opportunity> oppList = [SELECT Id, StageName FROM Opportunity WHERE OwnerId
= :ownerId AND StageName = 'Closed Won'];
if ( !oppList.isEmpty() ) {
Integer oppoCount = oppList.size();
System.debug( 'Total number of "Closed Won" Opportunities: ' + oppoCount );
}
}
}
2. If-Else Statement in Salesforce Apex
In Salesforce Apex, the if-else statement executes specific blocks of code based on whether a condition is evaluated as true or false. This allows your code to make decisions and take actions based on the logic you define. Here, in the else block, the false part gets executed.
Syntax:
if ( Condition ){
// true codition;
}
else{
// false codition;
}Here, we will use the same example, but this time, after fetching a record using SOQL, no record will be available in the list. Then, we will add an else block to the above Apex code and execute the code.
// In the list there is no any record available.
if ( !oppList.isEmpty() ) {
Integer oppoCount = oppList.size();
System.debug( 'Total number of "Closed Won" Opportunities: ' + oppoCount );
}
else{
System.debug( ' There is no any record avaible in the List' );
}
3. Else-If Statement / Nested If-Else Statement in Salesforce Apex
The Else-If statement is not a standalone concept; however, when we have multiple conditions to check for truth or falsity, we need to add them using the Else-If statement, which is also known as the nested If-Else statement in Salesforce Apex.
Syntax:
if (condition1) {
// execute if condition1 is true;
} else if (condition2) {
// Execute condition2;
} else if (condition3) {
// Execute condition3;
} else {
// code to be executed if all conditions are false;
}For example, you have three integers and want to find the smallest no from those integers. Here, I declared three integers, then used if and else if conditions to check the smallest number and display the result accordingly.
Integer x=20, y=30, z=10;
if ( x<y && x<z ) {
System.debug( 'Smallest No is X : '+x );
}
else if ( y<x && y<z ) {
System.debug( 'Smallest No is Y : '+y );
}
else {
System.debug ( 'Smallest No is Z : '+z );
} 
4. Switch Statement in Salesforce Apex
The switch statement is used when we need to compare a variable against multiple potential values. It’s more efficient and readable than using multiple if-else conditions.
Syntax:
switch on variable {
when value1 {
// execute if variable equals value1;
} when value2 {
// execute if variable equals value1;
} when else {
// code to be executed if variable doesn’t match any value;
}
}For example, we want to display the message according to opportunity stages. So here, I declare the string data type as stage and assign it a ‘Closed Won’ value.
Then, the switch on stage is a conditional statement that decides on which basis the logic will be executed. We have assigned a value to the stage, and according to that value, the switch block will execute.
Now, execute the apex code below to see the output.
public class SwitchDemo {
public void SwitchMethod() {
String stage = 'Closed Won';
switch on stage {
when 'Prospecting' {
System.debug ( 'Initial Stage' );
}
when 'Closed Won' {
System.debug ( 'Won the Opportunity' );
}
when else {
System.debug ( 'Other Stage' );
}
}
}
}In the switch statement, we assigned the closed won value to the stage. According to that value, you can see the closed won block executed with the message we provided in the debug method.

Loops in Salesforce Apex
In Salesforce Apex, loops are the same as other programming languages, which are used to execute a block of code repeatedly based on a condition. They help automate repetitive tasks, such as processing a collection of records or performing calculations.
Types of Loops in Salesforce Apex
The following are the types of loops in Salesforce Apex:
- for Loop in Salesforce Apex
- for each Loop in Salesforce Apex
- while Loop in Salesforce Apex
- do-while Loop in Salesforce Apex
1. for Loop in Salesforce Apex
In Salesforce Apex, a for loop is used to repeat a block of code a specific number of times or to iterate over a range of values. Once the loop executes the number of times that you provided, it stops executing. It consists of three main parts: initialization, condition, and increment.
Syntax:
for ( initialization; condition; increment ) {
// logic;
}For example, here, we want to display the numbers from 1 to 20, which is divisible by 3. We can use a for loop.
In the Apex code below, I create a for loop. Then, initialized with 0, we want to display the range of numbers from 1 to 20; for that, we added the condition i = 20. To increase the number, we use i++.
Then, to find the number that is divisible by 3, we need to use math class and mod function because the % operator is not supported in Salesforce Apex.
As you execute the below Apex for loop, you will get the numbers that are divisible by 3.
for ( Integer i = 0; i <= 20; i++ ) {
if ( math.mod(i, 3) == 0 ) {
System.debug(' ' +i);
}
2. for each Loop in Salesforce Apex
In Salesforce Apex, a for-each loop is mainly used in SObjects to iterate over collections like lists, sets, or maps.
Syntax:
for ( DataType variableName : collection ) {
// logic;
}For example, we want to fetch the account records with warm account ratings and display them using Salesforce Apex programming.
In the Apex code below, I declare a list of accounts that store account records whose rating is warm and add a limit of seven records. After that, in the for each loop, the list of records is assigned to acc, which is an instance of the account object. Using that instance, we display the records that we want.
List<Account> accList = [ SELECT Id, Name, Rating FROM Account WHERE Rating = 'warm'
LIMIT 7 ];
for ( Account acc : accList ) {
System.debug( ' Account Name : '+acc.Name + ' Rating : '+acc.Rating );
} First, I will show what happens if you don’t use each loop to display the records.

Then, as you execute the for each loop, the output will be as shown in the image below.

3. while Loop in Salesforce Apex
A while loop in Salesforce Apex is a control flow statement that allows code to be executed repeatedly as long as a given condition remains true. The condition is checked before each iteration, and the loop will continue running until the condition becomes false.
Syntax:
while (condition) {
// logic;
}For example, we want to display the even numbers between a particular range and their sum. So, here in a while, we enter the condition, and then in the loop, we need to enter the logic that you want to execute.
Integer startno = 2, sum=0;
while (startno <= 20) {
System.debug(+startno);
startno = startno + 2;
sum = sum + startno;
}
System.debug( 'Sum of first 20 Even no is :' +sum );
}
4. do-while Loop in Salesforce Apex
A do-while loop in Salesforce Apex is similar to a while loop, but the difference is that the code block inside the loop is executed at least once before the condition is checked. The condition is evaluated after each iteration, so the loop guarantees one execution even if the condition is initially false.
Syntax:
do {
// logic;
} while (condition);For example, we want to process a batch of records and stop when no more records are needed. Here, we defined the batchSize variable’s specified size (batchSize = 10). It is useful when you need to perform operations on many records but don’t want to load them all simultaneously.
The offset starts at 0 and is used to “skip” records during each query. It is incremented by batchSize (which is 10) after each iteration. Then, the List is declared to store the contact records.
Then, in the do block, we used a loop to iterate over the list by using an instance of the contact object and displaying the record.
After processing each batch of contacts, the offset is incremented by batchSize, so the next query skips the already processed contacts.
Finally, the while condition we provided means the loop continues until conList is empty, meaning no more contacts are left to process.
List<Contact> contacts;
Integer offset = 0;
Integer batchSize = 10;
List<Contact> conList = new List<Contact>();
do {
conList = [ SELECT Id, Name FROM Contact LIMIT :batchSize OFFSET :offset ];
for ( Contact c : conList ) {
System.debug( ' Contact Name : ' + c.Name );
}
offset = offset + batchSize;
} while ( !conList.isEmpty() );As you execute the above Apex code, you can see the output, which displays the contact names available in the contact list.

Conclusion
I hope you have got an idea about logical and looping statements in Salesforce Apex Programming. In that, we have seen which logical and looping statements are in Salesforce Apex and how to declare them and use them to implement complex business logic, automate processes, and handle bulk operations.
You may like to read:
- Convert String to Datetime in Salesforce Apex
- Get Current Datetime in Apex Salesforce
- Apex Trigger Handler and Helper Class in Salesforce
- Object Oriented Programming in Salesforce Apex
- Trigger Handler Pattern in Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.