Control Flow & Logic in Apex

Share

Conditional Statements: if / else, switch

What Are Conditional Statements?

Conditional statements allow Apex to make decisions based on conditions.

Simple Explanation

“If this condition is true, do this. Otherwise, do something else.”


if / else Statement

Real-Life Example

If your bank balance is enough → you can buy a product.
Otherwise → you cannot.

Code Example

Integer balance = 500;

if (balance >= 300) {
    System.debug('Purchase allowed');
} else {
    System.debug('Insufficient balance');
}

switch Statement

When to Use switch

Use switch when you have multiple fixed conditions.

Real-Life Example

Different customer types get different discounts.

Code Example

String customerType = 'Gold';

switch on customerType {
    when 'Gold' {
        System.debug('20% discount');
    }
    when 'Silver' {
        System.debug('10% discount');
    }
    when else {
        System.debug('No discount');
    }
}

Gist (Quick Revision)

  • if / else → best for simple decisions

  • switch → best for multiple known values


Loops: for / while / do-while

What Are Loops?

Loops allow Apex to repeat actions until a condition is met.

Simple Explanation

Loops save time by doing the same task again and again automatically.


for Loop

Real-Life Example

Send emails to all customers in a list.

Code Example

for (Integer i = 1; i <= 3; i++) {
    System.debug('Email sent ' + i);
}

while Loop

When to Use

Use while when you don’t know in advance how many times the loop will run.

Code Example

Integer count = 1;

while (count <= 3) {
    System.debug('Count is ' + count);
    count++;
}

do-while Loop

Key Difference

do-while runs at least once, even if the condition is false.

Code Example

Integer number = 5;

do {
    System.debug('This runs at least once');
} while (number < 3);

Gist (Quick Revision)

  • for → known number of repetitions

  • while → unknown repetitions

  • do-while → must run at least once


Loop Control Statements: break & continue

What Is break?

break stops the loop completely.

Real-Life Example

Stop searching once you find the item.

Code Example

for (Integer i = 1; i <= 5; i++) {
    if (i == 3) {
        break;
    }
    System.debug(i);
}

What Is continue?

continue skips the current iteration and moves to the next one.

Real-Life Example

Skip weekends when counting working days.

Code Example

for (Integer i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;
    }
    System.debug(i);
}

Gist (Quick Revision)

  • break → stop loop entirely

  • continue → skip current step

  • January 5, 2026