Tag Archives: Switch Statement

Salesforce Apex Switch Statement

From Summer ’18 Release Apex now supports switch statement, that tests whether an expression matches one of several values and branches accordingly.

Syntax:

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 {		  // when else block, optional
        // code block 4
    }
}

Example:

for(Integer i=1; i<=5; i++){
    Switch on i {
        when 1,2{
            System.debug('case 1 and 2');
        }
        when 5{
            System.debug('case 5');
        }
        when else{
            System.debug('case 3 and 4');
        }
    }
 }

The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the code block for the when else block is executed. If there isn’t a when else block, no action is taken.