Salesforce Apex If Else, Nested If, and Switch Case Examples : Shubham
by: Shubham
blow post content copied from SalesForce FAQs
click here to view original post
### Summary of Conditional Statements in Salesforce Apex In Salesforce Apex, conditional statements help developers make decisions in their code based on specific conditions. These statements allow for logical control of program execution, enabling actions to be taken depending on whether conditions are met. #### Key Conditional Statements: 1. **If Statement**: Executes a block of code if a specified condition is true. - **Example**: Checking if a list of opportunities is not empty and then counting the records. 2. **If-Else Statement**: Executes one block of code if a condition is true, and another block if it is false. - **Example**: If there are no records in the list, it displays a message indicating that. 3. **Else-If Statement (Nested If-Else)**: Allows checking multiple conditions in sequence. - **Example**: Finding the smallest number among three integers using multiple conditions. 4. **Switch Statement**: Compares a variable against multiple possible values and executes corresponding code blocks. - **Example**: Displaying messages based on different opportunity stages. #### Conclusion Conditional statements are essential in Salesforce Apex for automating business logic, such as applying discounts, sending notifications, or performing validations. Understanding how to use these statements effectively can significantly enhance your coding capabilities within the Salesforce platform. ### Additional Information - **Use Cases**: Conditional statements can be applied in various scenarios like managing discounts based on purchase amounts, validating user inputs, or controlling the flow of data processing in triggers. - **Best Practices**: Always ensure conditions are clearly defined to avoid logical errors in your code. ### Relevant Hashtags for SEO #Salesforce #Apex #ConditionalStatements #IfElse #SwitchCase #Programming #SalesforceDevelopment #CodeExamples #BusinessLogic #SoftwareDevelopment #TechTutorials
In Salesforce Apex, conditional statements are very useful when you need to make decisions based on certain conditions.
For example, a company wants to give discounts to customers based on their purchase amount. As a Salesforce developer, I write an Apex if-else statement to check the customer’s purchase amount.
- If the purchase is more than $50,000, the customer gets a 20% discount.
- If the purchase is between $20,000 and $50,000, the customer gets a 10% discount.
- Otherwise, no discount is applied.
In this article, we will learn about conditional statements in Salesforce Apex. In this, I will explain If-Else, Nested If, and Switch Case statements, their syntax, and provide examples to use in Salesforce Apex code.
Conditional Statements in Salesforce Apex
Conditional statements in Salesforce Apex are used to make decisions in Apex code, allowing developers to program the code to execute specific actions only when certain conditions are met.
Logic control in Salesforce Apex includes conditional statements that help manage execution flow based on specific conditions
The most common conditional statements are:
- 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 checks the defined condition and executes a block of code if the condition is true.
Syntax: Declare an If Statement in Salesforce Apex
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 collection to store opportunity records that we retrieved using a SOQL query. Now, using the if condition, we will check whether there is any record available on the list.
If a record is available, execute the if block, which returns the record count stored in the declared integer variable.
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 );
}
}
}

In this way, we can use the if conditional statement in Salesforce Apex to execute the if block when the declared condition is true.
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 perform actions based on the logic you define.
- If the condition in the if block is true, that block of code will execute.
- If the condition is false, the else block will execute instead.
- Since the else block has no condition, it always runs when the if block does not.
Syntax: Declare an If-Else Statement in Salesforce Apex
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. That means the condition defined in the if block gets false.
Then, if the if block is not executed, the else block is executed in the above Apex 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' );
}

In this way, we can use the if-else conditional statement in Salesforce Apex to execute the else block when the if block condition is false.
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: Else-If Statement / Nested If-Else Statement in Salesforce Apex
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 which number was the smallest 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 Statement in Salesforce Apex
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 based on the opportunity stages. Here, I declare the string data type as ‘stage’ and assign it the value ‘Closed Won’.
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.

Conclusion
I hope you have got an idea about conditional statements in Salesforce Apex. They allow your code to make decisions and take actions based on specific conditions.
Using If-Else, Nested If, and Switch Case statements, you can control the flow of your code. Conditional statements are very useful for automating business logic such as discounts, notifications, or validations.
You may like to read:
- Create Rollup Summary on Lookup Relationship Using Salesforce Apex Trigger
- Auto-Populate Fields Using Apex Trigger in Salesforce
- Trigger Helper Class in Salesforce
- Loops in Salesforce Apex: For, While, Do-While Examples
The post Salesforce Apex If Else, Nested If, and Switch Case Examples appeared first on SalesForce FAQs.
September 14, 2025 at 08:42PM
Click here for more details...
=============================
The original post is available in SalesForce FAQs by Shubham
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Post a Comment