In Salesforce Apex, Ternary Operators are part of the Apex conditional statements. They serve as a shorthand replacement for if-else conditionals, making the code logic more understandable.
In this Salesforce tutorial, we will learn about Ternary operators in Salesforce Apex and how to use them as conditionals in our code logic.
What are Ternary Operators in Salesforce Apex?
In Salesforce Apex, ternary operators are used as a one-liner replacement for if-else conditional statements. The logic in the ternary operators works similarly to if-else conditionals. It evaluates a condition and returns one value if it is true and another if it is false.
For example, if x is true, y is the result. Otherwise, z will be the result. Let’s see how we define this condition using the ternary operator in Salesforce Apex. The ternary operator condition is written as follows.
X ? Y : Z ;
In the above expression, X is the condition evaluated as true or false. If the condition is true, the returned value will be Y; otherwise, it will be Z.
Use Case of Ternary Operator in Salesforce Apex
In the code below, we will understand the implementation of the ternary operator through an example. We will define the condition that when the Score (integer) value is less than 30, the return value will be True or False.
Integer score = 85;
String result = score >= 30 ? 'Passed' : 'Failed';
System.debug(result);
In the above code, we have defined an integer value of 85, which is greater than 30 according to the condition. Thus, the expected output will be the string “Passed.“

When I change the integer value to less than 30, the expected output will be the string “Failed” according to the defined condition.

This way, you use and execute the ternary operator in your Apex code, simplify the code structure, and make it easy to understand.
Handling Null Values in Ternary Operators in Salesforce
In Salesforce Apex, we can also handle null values in the ternary operator. To achieve this, we can set the condition parameters so that when the value is null, the output defaults to the specified value.
Apex code:
Default Value = "APEX";
String input = null;
String result = (input != null) ? input : Default Value ;
System.debug(result);
According to the condition we have put in the above code, if the input value is null, then it will take the input as the Default Value.
