Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
19 views
in Salesforce by (11.9k points)

Instead of this basic structure with IF / THEN / ELSEIF / ELSE

int month = 8;

String monthString;

if (month == 1) {

    monthString = "January";

} else if (month == 2) {

    monthString = "February";

}

...  // and so on

it would be nice to have

  int month = 8;

    String monthString;

    switch (month) {

        case 1:  monthString = "January";

                 break;

        case 2:  monthString = "February";

                 break;

        ..... // and so on

        case 12: monthString = "December";

                 break;

        default: monthString = "Invalid month";

                 break;

    }

This would increase readability and make it easier to debug due to clarity of intent.

closed

1 Answer

+3 votes
by (32.1k points)
edited by
 
Best answer

Salesforce does support switch and Case statement in Salesforce. The switch statement is used to test whether an expression matches one of many values and branches respectively.

Are you interested in learning Salesforce from scratch! Have a look at this interesting video on Salesforce provided by Intellipaat:

The syntax for using Switch and case in Salesforce is:

switch on expression { when value1 { // when block 1 // code block 1 when value2 { // when block 2 // code block 2 when value3 { // when block 3 // code block 3 when else { // default block, optional // code block 4 }

Also, the when value can either be a single value, multiple value, or sObject types. For example:

When Value1, Value2 { //code block }

Go for this in-depth job-oriented Salesforce admin certification now!

Related questions

0 votes
1 answer
0 votes
1 answer
asked Dec 22, 2020 in SQL by Appu (6.1k points)
+1 vote
2 answers
0 votes
1 answer
0 votes
1 answer
asked Sep 29, 2019 in Java by Shubham (3.9k points)

Browse Categories

...