Any Seasonal developer can tell us about the switch statement that is used in various programming languages. It is like multiple if…elseif…else statements. However, this feature was missing in APEX programming. Yes, the platform did not support switch case statements. It was not until the Summer ’18 release that this statement was added to the Platform. Even though it is a part of the language the syntax is a little bit different as compared to the standard switch case. This is what we will see today, how to use the switch statement in APEX.

APEX Code

Let’s jump directly to the code here. The code below is the example code for the switch statement.

public class SwitchTest {
    public String testStr { get; set;}
    
    public String getOutputString(){
        switch on testStr {
            when 'First' {		// when block 1
                return 'Option 1';
            }
            when 'Second' {		// when block 2
                return 'Option 2';
            }
            when null {
                testStr = 'First';
                return 'Option 1';
            }
            when else {		  // when else block, optional
                return 'Other Option';
            }
        }
    }
    
    public list getSelectOptions(){
        list options = new list();
        options.add(new selectOption('First', 'First'));
        options.add(new selectOption('Second', 'Second'));
        options.add(new selectOption('Third', 'Third'));
        options.add(new selectOption('Fourth', 'Fourth'));
        options.add(new selectOption('Fifth', 'Fifth'));
        return options;
    }
    
    public void dummy(){
        
    }
}

One thing that needs to be kept in mind is that we do not need the break statement in this code. The scope does the work. However, the flow will also not be transferred from one case (or when in this example) block to subsequent block.

VisualForce Code

<apex:page controller="SwitchTest">
    <apex:form >
        <apex:selectList size="1" value="{!testStr}">
             <apex:selectOptions value="{!SelectOptions}"/>
             <apex:actionSupport event="onchange" action="{!dummy}"/>
        </apex:selectList>
        <apex:outputText value="{!OutputString}"/>
    </apex:form>
</apex:page>

In this page, we are just showing the string returned by the switch code. The code takes the string from select option and shows the corresponding string on the VF page.

Output

The Output of my code will look something like this.

Support

That’s all about switch statement in APEX, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views about this blog in the comments section below.

Leave A Reply

Please verify that you are not a robot.

Tell us about Your Company

How can we help you with your business?




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home