How to use the Conditional / Ternary operator in Salesforce Apex Class

? : x ? y : z Ternary operator (Right associative). This operator acts as a short-hand for if-then-else statements. If x, a Boolean, is true, y is the result. Otherwise z is the result. Note that x cannot be null.

Sample Syntax to use Conditional / Ternary operator in Apex Class

Integer Result = SomeCondition ? Value1 : Value2;

Example for Ternary operator in Apex Class:

Integer ListPrice = 50;
Integer SalesPrice = 100;
Integer TotalAmount = ListPrice > 50 ? ListPrice : SalesPrice;
System.debug(‘::TotalAmount::’+ TotalAmount);

Output: 19:48:26:002 USER_DEBUG [5]|DEBUG|::TotalAmount::100

Example for Ternary operator in Apex Class:

String WebSite = ‘’;
String WebSiteResult = WebSite != null ? WebSite : ‘’;
System.debug(‘::WebSiteResult::’+ WebSiteResult);

Output: 19:52:11:001 USER_DEBUG [3]|DEBUG|


Refer the All the Expression Operators in Salesforce:-


Written by 

2x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

Your email address will not be published. Required fields are marked *