Apex Control Flow Statements
Apex Control Flow Statements are fundamental constructs in Salesforce's Apex programming language that allow developers to control the execution path of their code based on conditions, loops, and branching logic. These are essential for Process Automation and Logic in the Platform Developer I certi… Apex Control Flow Statements are fundamental constructs in Salesforce's Apex programming language that allow developers to control the execution path of their code based on conditions, loops, and branching logic. These are essential for Process Automation and Logic in the Platform Developer I certification. **Conditional Statements:** 1. **if-else:** Executes code blocks based on Boolean conditions. You can chain multiple conditions using else-if for complex decision-making. 2. **switch:** Introduced in later Apex versions, switch statements evaluate an expression against multiple possible values, providing cleaner syntax than multiple if-else chains. Switch supports sObject types, enums, Strings, Integers, and Longs. **Loop Statements:** 1. **for loop (Traditional):** Iterates using an initializer, condition, and increment expression — for(Integer i=0; i<10; i++). 2. **for loop (Collection):** Iterates over lists or sets — for(Account a : accountList). This is heavily used in trigger handlers to process bulk records efficiently. 3. **SOQL for loop:** Iterates over query results in batches of 200 records, helping avoid heap size limits — for(Account a : [SELECT Id FROM Account]). 4. **while loop:** Repeats execution as long as a condition remains true. 5. **do-while loop:** Similar to while but guarantees at least one execution before checking the condition. **Branching Statements:** 1. **break:** Exits the current loop immediately. 2. **continue:** Skips the remaining code in the current loop iteration and moves to the next iteration. 3. **return:** Exits the current method, optionally returning a value. **Exception Handling:** - **try-catch-finally:** Controls flow when exceptions occur. The try block contains code that might throw exceptions, catch handles specific exceptions, and finally executes regardless of whether an exception occurred. Understanding these control flow statements is critical for writing efficient, bulkified Apex code that respects governor limits — a key focus area for the Platform Developer I exam.
Apex Control Flow Statements – Salesforce Platform Developer 1 Exam Guide
Why Apex Control Flow Statements Matter
Control flow statements are the backbone of any Apex program. They determine the order in which individual statements, instructions, or function calls are executed. On the Salesforce Platform Developer 1 exam, questions on control flow are common because they test your fundamental understanding of how Apex logic works. Without a solid grasp of these statements, you cannot write triggers, classes, or batch jobs that behave correctly under varying conditions. Mastering control flow is essential for building robust business logic on the Salesforce platform.
What Are Apex Control Flow Statements?
Control flow statements in Apex allow developers to dictate the path of execution through code based on conditions, loops, and branching. They fall into three main categories:
1. Conditional (Decision-Making) Statements
if / else if / else
The most fundamental conditional construct. It evaluates a Boolean expression and executes a block of code if the expression is true.
Example:
Integer score = 85;
if (score >= 90) {
System.debug('Grade: A');
} else if (score >= 80) {
System.debug('Grade: B');
} else if (score >= 70) {
System.debug('Grade: C');
} else {
System.debug('Grade: F');
}
Key points:
- Conditions are evaluated top-down; the first true condition's block executes and the rest are skipped.
- The else block is optional and serves as a catch-all.
- You can nest if statements inside other if statements.
switch on (Switch Statements)
Introduced in later Apex versions, the switch on statement provides a cleaner alternative to multiple if-else chains when comparing a single expression against many possible values.
Example:
Integer dayOfWeek = 3;
switch on dayOfWeek {
when 1 { System.debug('Monday'); }
when 2 { System.debug('Tuesday'); }
when 3 { System.debug('Wednesday'); }
when 4 { System.debug('Thursday'); }
when 5 { System.debug('Friday'); }
when else { System.debug('Weekend'); }
}
Key points:
- switch on works with Integer, Long, String, sObject, and Enum types.
- There is no fall-through behavior (unlike Java or C#). Each when block is independent.
- when else is the default case (similar to else in if-else).
- You can group multiple values in a single when clause: when 6, 7 { ... }
- For sObject types, you can use when Account a { ... } to match on the sObject type and assign it to a variable.
2. Looping (Iteration) Statements
for loop (Traditional)
The classic C-style for loop with an initialization, condition, and increment expression.
Example:
for (Integer i = 0; i < 5; i++) {
System.debug('Iteration: ' + i);
}
for loop (List/Set Iteration – Enhanced For Loop)
Iterates directly over elements in a collection (List, Set, or query results).
Example:
List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};
for (String fruit : fruits) {
System.debug(fruit);
}
for loop (SOQL For Loop)
A special form that processes query results in batches of 200 records, which helps avoid heap size limits.
Example:
for (Account acc : [SELECT Id, Name FROM Account WHERE Industry = 'Technology']) {
System.debug(acc.Name);
}
Key point: The SOQL for loop is critically important for governor limits. It retrieves records in chunks of 200 internally, keeping the heap size manageable when processing large data sets.
while loop
Executes a block of code repeatedly as long as the specified Boolean condition is true. The condition is checked before each iteration.
Example:
Integer count = 0;
while (count < 3) {
System.debug('Count: ' + count);
count++;
}
do-while loop
Similar to a while loop, but the condition is checked after each iteration. This guarantees the loop body executes at least once.
Example:
Integer count = 0;
do {
System.debug('Count: ' + count);
count++;
} while (count < 3);
3. Branching (Jump) Statements
break
Immediately exits the innermost loop or switch block.
Example:
for (Integer i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.debug(i);
}
// Output: 0, 1, 2, 3, 4
continue
Skips the rest of the current loop iteration and moves to the next iteration.
Example:
for (Integer i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
System.debug(i);
}
// Output: 0, 1, 3, 4
return
Exits the current method. If the method has a return type, a value must be returned. For void methods, return; simply exits the method.
throw
Used to throw an exception, immediately interrupting the current flow and transferring control to the nearest matching catch block.
Example:
if (someValue == null) {
throw new CustomException('Value cannot be null');
}
How Control Flow Works in Practice
Understanding control flow means being able to mentally (or on paper) trace through code and predict the output. Consider this combined example:
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer sum = 0;
for (Integer num : numbers) {
if (num > 8) {
break;
}
if (Math.mod(num, 2) == 0) {
continue;
}
sum += num;
}
System.debug('Sum: ' + sum);
// Traces: 1 (added), 2 (skipped – even), 3 (added), 4 (skipped), 5 (added), 6 (skipped), 7 (added), 8 (skipped), 9 (break – loop exits)
// Sum = 1 + 3 + 5 + 7 = 16
Common Pitfalls to Watch For
- Infinite loops: Forgetting to increment a counter in a while or do-while loop causes an infinite loop, which will hit the CPU time governor limit.
- Null pointer exceptions in conditions: Always check for null before accessing properties of an object in an if condition.
- Governor limits with loops: Never place DML statements or SOQL queries inside a loop. This is a top exam topic.
- Off-by-one errors: Using < vs <= in loop conditions can produce unexpected iteration counts.
- Unreachable code: Code placed after a return, break, or throw statement will not execute and may cause a compilation error.
Control Flow and Governor Limits
Apex runs in a multi-tenant environment, so understanding how control flow interacts with governor limits is essential:
- Use SOQL for loops to handle large record sets efficiently.
- Avoid placing SOQL queries inside for loops (bulkify your code).
- Use collections (Lists, Maps, Sets) to gather data before/after loops, then perform a single DML operation outside the loop.
- Be aware that deeply nested loops multiply iteration counts, which can lead to exceeding CPU time limits.
Exam Tips: Answering Questions on Apex Control Flow Statements
1. Trace the code carefully: Many exam questions present a code snippet and ask "What is the output?" Trace through each line step by step. Pay close attention to the order of conditions in if-else chains and where break/continue statements are placed.
2. Know the difference between while and do-while: The exam frequently tests whether you know that a do-while loop always executes at least once, while a while loop may execute zero times if the condition is initially false.
3. Understand switch on behavior: Remember that Apex switch statements have no fall-through. Each when block is self-contained. Know the supported data types (Integer, Long, String, sObject, Enum).
4. Identify governor limit violations: If a question shows a SOQL query or DML statement inside a for loop, that is almost certainly the wrong answer or the problematic code. Always choose the bulkified approach.
5. Watch for break vs. continue: Break exits the entire loop; continue skips only the current iteration. Questions may try to confuse these two behaviors.
6. Pay attention to variable scope: Variables declared inside a loop or if block are not accessible outside that block. The exam may test whether code compiles based on variable scope.
7. SOQL for loop syntax: Know that for (Account a : [SELECT ...]) processes records one at a time (in chunks of 200 behind the scenes), while for (List<Account> accounts : [SELECT ...]) gives you the list of 200 records at a time for manual batch processing.
8. Nested if vs. combined conditions: Understand that if (a && b) is equivalent to nesting if (a) { if (b) { ... } }. The exam may present both styles and ask which produces the same result.
9. Ternary operator: Although not a full control flow statement, the ternary operator condition ? valueIfTrue : valueIfFalse is a concise way to assign values conditionally. Know its syntax for the exam.
10. Exception handling flow: Understand that try-catch-finally is a control flow mechanism. Code in the finally block always executes, whether an exception was thrown or not. If a question asks what happens after a throw statement, look for the catch block.
11. Eliminate wrong answers: When unsure, eliminate choices that contain obvious errors like SOQL in loops, infinite loops, or unreachable code. This increases your odds even when the logic is complex.
12. Practice with anonymous Apex: Before the exam, practice tracing and running code snippets in the Developer Console's Execute Anonymous window. Building muscle memory for reading control flow will speed up your exam performance significantly.
Summary
Apex control flow statements – including if/else, switch on, for, while, do-while, break, continue, return, and throw – form the foundation of all Apex programming. For the Platform Developer 1 exam, focus on being able to trace code execution paths, understand loop behaviors and their governor limit implications, and distinguish between similar constructs. Practice reading code carefully and methodically, and you will be well-prepared to answer these questions confidently.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!