Wednesday, January 2, 2019

Switch Statement in Apex


This post explains about switch statement in Salesforce
Apex provides a 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
    }
}
Apex switch statement expressions can be one of the following types.
  • Integer
  • Long
  • sObject
  • String
  • Enum
Example
String strDayName = 'Sunday';

Switch on strDayName {
    when 'Sunday' {
        System.debug('today is Sunday');
    }
    when 'Monday' {
        System.debug('today is Monday');
    }
    when else {
        System.debug('No Value match');
    }
}
The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, then when else code block is executed. If there isn’t a when else block, no action is taken.
Resource
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_switch.htm

3 comments:

  1. can we use break statement in switch program in salesforce.

    ReplyDelete
    Replies
    1. yes . it is same as in other programming languages

      Delete
    2. no you can't use break here because it automatically terminated after meting the criteria

      Delete