function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RedSalesRedSales 

Using Conditional (If-Else) Statements In A String Concatenation

Hello,

 

I wish to include an "if" statement in a section of my code where I am building up a string by concatenating data.

The purpose of the "if" statement is to check if a value is null, & if not to then use the function "String.escapeSingleQuotes" on it.

 

An example is as follows (Note you can ignore the fact I have no single quotes in my example as it's just strings made up for the example. I will be taking my value from object fields so in my actual live system there is a chance that a single quote may appear)

 

 

String buildString = 'Just a test string to check concatenation';
String  tester = 'Test String';
buildString = buildString + 'hello : ' + if(tester=null) tester; else String.escapeSingleQuotes(tester); + ' : goodbye';

 

String buildString = 'Just a test string to check concatenation';String  tester = 'Test String';
buildString = buildString + 'hello : ' + if(tester=null) tester; else String.escapeSingleQuotes(tester); + ' : goodbye';

 

 

When I run the above code I get an error as follows.

 

"Compile error at line 4 column 41

unexpected token: 'if'"

 

Does anyone know why my error is occuring in the above code & how I can resolve it? I'm going to have about 30 values to check & add to my string while building it so would like to do in one line each time as opposed to different lines 

 

 

if ([Boolean_condition])

// Statement 1

else

// Statement 2

 

 

Thanks in advance for your suggestions!

Best Answer chosen by Admin (Salesforce Developers) 
sebcossebcos

Hi, 

the syntax is incorrect.

The if statement in Apex is not an expression and does not return a value.

To learn more about expressions please read:

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/langCon_apex_expressions_understanding.htm

 

What you need is the ternary operator "boolean x ? y : z" which is an expression :

http://www.salesforce.com/us/developer/docs/apexcode/index_Left.htm#StartTopic=Content/langCon_apex_expressions_operators_understanding.htm

 

I have rewritten your code to use the ternary operator:

 

 

 

String buildString = 'Just a test string to check concatenation';
String  tester = 'Test String';
buildString = buildString + 'hello : ' + (tester== null ? tester : String.escapeSingleQuotes(tester)) + ' : goodbye';