Beginner 15 min read

Switch Statements

By the end of this lesson, you'll be able to:

  • Write a switch statement as an alternative to a long if/else if chain
  • Use when blocks and a default block correctly
  • Decide when switch is clearer than if/else if

Prerequisites: "Logical Operators in Practice"

The basic shape

String region = 'EMEA';

switch on region {
    when 'AMER' {
        System.debug('Americas team');
    }
    when 'EMEA' {
        System.debug('Europe, Middle East, Africa team');
    }
    when 'APAC' {
        System.debug('Asia-Pacific team');
    }
    when else {
        System.debug('Unknown region');
    }
}

switch on region names the value being checked once; each when tests it against one possible match. when else is the catch-all, playing the same role a trailing else plays in an if-chain.

When switch beats if/else if

Compare the switch above to the equivalent if-chain:

if (region == 'AMER') {
    System.debug('Americas team');
} else if (region == 'EMEA') {
    System.debug('Europe, Middle East, Africa team');
} else if (region == 'APAC') {
    System.debug('Asia-Pacific team');
} else {
    System.debug('Unknown region');
}

Both work identically. switch reads more clearly once you're checking the same single value against many possibilities — the repeated region == in the if-chain adds visual noise that switch on region avoids entirely.

Trade-offs and when NOT to use this

switch only compares one value for equality against fixed matches — it can't express range checks like "greater than 50" the way if/else if can. Reach for switch specifically when you're matching one variable against several discrete, exact values; use if/else if for ranges or compound conditions.

Exercise

Declare String orderStatus = 'SHIPPED'. Write a switch statement debugging a different message for 'PENDING', 'SHIPPED', 'DELIVERED', and a when else for anything else.

Show hint

switch on orderStatus { when 'PENDING' { ... } when 'SHIPPED' { ... } ... }

APEX

Switch Statements Quiz

1. When is a switch statement generally clearer than if/else if?

Log in to submit the quiz and save your score.

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A switch statement checks one value against several possible matches — often clearer than a long if/else if chain when every branch is testing the exact same variable for equality.