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

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

X?Y:Z
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 = ‘TheBlogReaders.com’;
String WebSiteResult = WebSite != null ? WebSite : ‘Google.com’;
System.debug(‘::WebSiteResult::’+ WebSiteResult);

Output: 19:52:11:001 USER_DEBUG [3]|DEBUG|::WebSiteResult::TheBlogReaders.com

 

Refer the All the Expression Operators in Salesforce:-

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_expressions_operators_understanding.htm

 

You may also like

Leave a Comment