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

 

Written by 

I am Sakthivel Madesh, a certified Salesforce Advanced Developer & Administrator working on Salesforce Technology since 2011. I am currently working in Techforce Services as Sr. Salesforce Developer. I have worked on multiple technologies Like PHP, Java, Salesforce, I am very passionate about Salesforce and to earn 15x Salesforce Certification. I love Trailhead for learning Salesforce Skill and Become a Trailhead 5x Ranger too. I Love to Learn & Share my Salesforce knowledge to Salesforce Learners/Beginner using My Blog and Salesforce Community.

Leave a Reply