In Apex, a switch statement is a control flow statement that evaluates an expression and executes code based on the value of the expression. The switch statement is used when you have multiple conditions to check and execute different blocks of code based on those conditions.
The syntax of a switch statement in Apex is as follows:
switch on (expression) {
when value1 {
// code block to execute when
expression equals value1
}
when value2 {
// code block to execute when
expression equals value2
}
when else {
// code block to execute when
expression does not equal any of the
specified values
}
}
In this syntax, expression is the expression to evaluate, and value1, value2, and so on are the values to compare the expression with. You can specify any number of when clauses, each with a different value to compare the expression with.
The when else clause is optional and specifies a default code block to execute when the expression does not equal any of the specified values.
Here is an example of a switch statement in Apex:
String dayOfWeek = 'Monday';
switch on (dayOfWeek) {
when 'Monday' {
System.debug('Today is Monday');
}
when 'Tuesday' {
System.debug('Today is Tuesday');
}
when 'Wednesday' {
System.debug('Today is Wednesday');
}
when 'Thursday' {
System.debug('Today is Thursday');
}
when 'Friday' {
System.debug('Today is Friday');
}
when else {
System.debug('Today is a weekend day');
}
}
In this example, the switch statement evaluates the dayOfWeek variable and executes the code block for the matching when clause. If the dayOfWeek variable does not match any of the specified values, the code block for the when else clause is executed.