Control Structures in salesforce Apex

Understanding Control Structures in Apex  – Tutorial 3

Spread the love

Control structures in Apex are like the decision-making tools that help your code make choices and perform actions based on certain conditions. Think of them as traffic signals directing the flow of your program. There are three main types of control structures you’ll encounter in Apex: if-else statements, loops, and switch statements.

If-Else Statements

If-else statements are like forks in the road. They allow your code to take different paths based on whether a condition is true or false. For example, if you want to check if a number is greater than 10, you can use an if-else statement:

Integer number = 15;
if (number > 10) {
    System.debug('The number is greater than 10');
} else {
    System.debug('The number is not greater than 10');
}

In this code, if the number is greater than 10, it will print one message, and if not, it will print another.

Loops

for (Integer i = 1; i <= 5; i++) {
System.debug(‘Iteration ‘ + i);
}

Loops are like repeating patterns. They allow your code to execute a set of instructions multiple times. There are two common types of loops in Apex: the for loop and the while loop.

In this for loop, the code inside it will be executed five times, and it will print the iteration number from 1 to 5.

Switch Statements

Switch statements are like multiple-choice questions. They let your code choose from several options based on the value of a variable. Here’s an example:

String fruit = 'apple';
switch (fruit) {
    case 'apple':
        System.debug('It's an apple.');
        break;
    case 'banana':
        System.debug('It's a banana.');
        break;
    default:
        System.debug('It's something else.');
}

In this code, the switch statement checks the value of the fruit variable and prints a message based on its value.

Control structures are essential in programming because they give your code the ability to make decisions, repeat tasks, and handle different scenarios. Whether you’re building a simple calculator or a complex business application, understanding and using control structures effectively in Apex is crucial to creating functional and intelligent programs. As you continue your Apex journey, you’ll find these control structures to be valuable tools for crafting dynamic and responsive solutions in Salesforce.

We can help you with job-oriented salesforce training with 100% practicals and assist you in certification exam preparation. Join our real-time project based Salesforce training, enroll for free demo!


0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Open Chat
1
Dear Sir/Madam
How can I help you?