Notes
Apex provides a switch statement that tests whether an expression matches one of several values and branches accordingly.
The when value can be a single value, multiple values, or sObject types.
Integer day = 4;
switch on day {
when 1,2,3,4,5 {
System.debug('Week Days');
}
when else {
System.debug('Weekend');}
}
The switch
statement evaluates the expression and executes the code block for the matching when
value. If no value matches, the when else code block is executed. If there isn’t a when else
block, no action is taken.
Integer day = 4;
switch on day {
when 1 {
System.debug('Monday');
}
when 2 {
System.debug('Tuesday');
}
when 3 {
System.debug('Wednesday');
}
when 4 {
System.debug('Thursday');
}
when 5 {
System.debug('Friday');
}
when 6 {
System.debug('Saturday');
}
when else {
System.debug('Sunday');}
}
Apex switch
statement expressions can be one of the following types.
- Integer
- Long
- sObject
- String
- Enum
When Blocks
Each when
block has a value that the expression is matched against. These values can take one of the following forms.
When Else Block
If no when
values match the expression, the when else
block is executed.
Note: If you include a when else
block, it must be the last block in the switch
statement.
More Examples:
Integer month = 4;
switch on month {
when 12 ,1,2 {
System.debug('Winter');
}
when 3,4,5 {
System.debug('Spring');
}
when 6,7,8 {
System.debug('Summer');
}
when 9,10,11{
System.debug('Autumn');
}
when else {
System.debug('Enter a number between 1 and 12');
}
}
More Examples:
Integer num = 13;
Integer remainder = Math.mod(num,2);
switch on remainder {
when 0 {
System.debug('Even Number');
}
when else {
System.debug('Odd Number');}
}