Salesforce Certified Platform Developer free question 4 / 10 · Domain 2: Process Automation and Logic
The following Apex is executed. Integer i = 3; String out = ''; switch on i { when 2, 3, 4 { out += 'A'; } when 5 { out += 'B'; } when else { out += 'C'; } } System.debug(out); What value appears in the debug log?
- ABC is logged
- A is logged
- AC is logged
- AB is logged
Show the answer and explanation
Answer: B
Why this is correct
The Apex Developer Guide topic "Switch Statements" says a switch statement evaluates its expression and runs the code block of the matching when clause. If nothing matches, the when else block runs. There is no fall-through: once a code block finishes, the switch is done. A single when clause can list several values separated by commas. Because i is 3, only when 2, 3, 4 runs and out becomes A.
Why the other options are wrong
"ABC is logged" … A switch runs the code block of one matching when clause and then exits. It does not run the clauses that follow.
"AC is logged" … The when else block runs only when no when value matches. 3 matches when 2, 3, 4, so when else is never reached.
"AB is logged" … This answer assumes execution falls through into the next when clause, as it does in Java when a break is missing. The guide says an Apex switch has no fall-through.
Takeaway
To run the same logic for several values, list the values in one when clause rather than stacking clauses and relying on fall-through as in Java. The switch expression can be an Integer, Long, sObject, String, or enum, and when else, if present, goes last.