This course is currently a work in progress. Please join the waitlist to receive regular updates.

Switch case statements in apex

Switch case statement checks a value against multiple predefined options (called cases). Depending on the matching case, it executes the corresponding block of code. If none of the cases match, a default block (optional) can be executed.

Following is an example of traffic lights and vehicle speed in a switch case statement.

Swith Case Statements

Branch the execution of the code based on predefined input values

Cases

Case 1 - traffic light is green

Executed when trafficLight is set to green.

To translate the above requirement as a switch case statement, use the following syntax:

Loading...

In the above example:

  • The variable trafficLight is the input variable for the switch case statement.
  • The values gree, yellow, read are the expected values.
  • If the input variable trafficLight receives one of the predefined values, the respective blocks is executed.
  • If the input variable trafficLight receives a value other than the predefined values, the else statement is executed.

Try It Yourself

Loading...