Salesforce Switch Statements
Switch Statements
A switch statement tests whether an expression matches one of the several cases.
Syntax:
switch(expression)x
value1
{
//statement
}
value2
{
//statement
}
value3
{
//statement
}
Default
Example:
integer num= 17;
switch on num
{
when 2{
system.debug('num is 4');
}
when -3
{
system.debug('num is -3');
}
when else{
system.debug('neither 2 nor -3');
}
}
Output:

Example:
integer place=1;
String medal_color; //null
switch on place
{
when 1{
medal_color='gold';
}
when 2{
medal_color='silver';
}
when 3{
medal_color='bronze';
}
when else{
medal_color=null;
}
}
if(medal_color!=null)
{
System.debug('you have scored '+medal_color+ 'medal.Congratulations!!');
}
else
{
System.debug('Work hard');
}
Output:

Example:
integer score=95;
switch on score
{
when 80,85,90,95{
System.debug('FIRST PLACE');
}
when 75,70
{
System.debug('SECOND PLACE');
}
when 65,60,55
{
System.debug('THIRD PLACE');
}
when else
{
System.debug('Better luck');
}
}
Output:

