I was working on a controller, and came across a question mark in the code. What is this used for? I've searched for it but haven't found what it is used for.

    string fieldAPIName = dfield.getName().endsWith('Id') && !dfield.isCustom() ? dfield.getName().removeEnd('Id') : dfield.getName();
    tempList.add(dfield.getLabel() + ':' + fieldAPIName);

2 Answers 2


It is called as ternary operator

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.

dfield.isCustom() ? dfield.getName().removeEnd('Id') : dfield.getName();

The above statement means that is if dfield.isCustom() is true dfield.getName().removeEnd('Id') value will be returned else dfield.getName() value will be returned.

  • what does x,y and z refer in the comment? Make sure everything is explained with an example.
    – Lokesh
    Commented Jul 19, 2019 at 13:26
  • Now it looks fine
    – Lokesh
    Commented Jul 19, 2019 at 13:35
  • 3
    @Lokesh If you read the answer properly, I gave the exact example which the OP the has asked for where dfield.isCustom() is x which is boolean, if it evaluates to true, then dfield.getName().removeEnd('Id') i.e. y will be returned else dfield.getName() i.e. z will be assigned. Commented Jul 19, 2019 at 13:37

Since Winter '21, the question mark is also used in Apex as a null-safe operator:

String myVal = a?.b // Evaluates to: a == null? Null : a.b

You may review the release notes (https://releasenotes.docs.salesforce.com/en-us/winter21/release-notes/rn_apex_SafeNavigationOperator.htm)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .