• Lessons Home
Topics
Community
  1. Lessons
  2. Flow Control
  3. Conditional Statements
  4. Switch Statements

      Switch Statements

      Switch Statements

      Long else if chains that compare the same variable over and over can be hard to read. Apex gives you the switch statement as a cleaner way to branch on the value of a single expression.

      Basic Structure

      You write switch on followed by the value to test. Each when block lists one or more values to match. The when else block runs when nothing else matches:

      Integer day = 3;
      
      switch on day {
          when 1 {
              System.debug('Start of the week');
          }
          when 6, 7 {
              System.debug('Weekend');
          }
          when else {
              System.debug('A weekday');
          }
      }
      

      Notice that one when can list several values separated by commas. Here 6 and 7 both map to the weekend branch.

      Only One Branch Runs

      Apex runs the first matching when block and then leaves the switch. Unlike some other languages, you do not write break after each branch, and there is no fall-through into the next one.

      Switching on Different Types

      You can switch on an Integer, a Long, a String, or an sObject type. The values in each when must match the type of the expression:

      String color = 'Green';
      
      switch on color {
          when 'Green' {
              System.debug('Go');
          }
          when 'Red' {
              System.debug('Stop');
          }
          when else {
              System.debug('Unknown');
          }
      }
      

      Why This Matters

      When you are choosing between several fixed values of one variable, a switch is easier to read than a stack of else if statements. Always include a when else branch so that unexpected values are handled cleanly.

      Apex Code Editor
      Sign in to Submit

      Welcome to Lightning Challenge!

      How It Works

      • • Write your solution in the code editor
      • • Connect your Salesforce org to test
      • • Submit to check if your solution passes
      • • Use hints if you get stuck

      Note

      Complete this lesson challenge to earn points and track your progress. The code editor allows you to implement your solution, and the tests will verify if your code meets the requirements.

      Wally Assistant

      Wally can't hear you

      Please sign in to access the AI Assistant

      Sign In