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
Anime LoverAnime Lover 

How to use string expression in IF condition Apex

Hi there,
I am stuck in my program, Actually I want to use String expression into the IF statement condition.
eg:
String expression1 = 'Annual_Rev__c != 0 && Status__c == "Closed"';
if(expression1 ){
System.debug('It Worked...!');
}

Is there any solution for this, Please let me know your thoughts on this.

Thanks,
Rahul​​​​​​​
AnkaiahAnkaiah (Salesforce Developers) 
Hi Anime,

What is the value you are trying to keep in expression1?

below is the if condition check for string.
If(!IsEmpty(expression1 ))

Regards,
Ankaiah
Suraj Tripathi 47Suraj Tripathi 47
Hi Anime Lover,

As I can see you are passing string value in if condition, but If-else only accepts boolean value.
So, please try the given code below.
String expression1 = 'Annual_Rev__c != 0 && Status__c == "Closed"';
    if(boolean.valueof(expression1)){
        system.debug('true');
    }else{
        system.debug('false');
    }

I hope you find the above solution helpful. If it does, please mark it as Best Answer to help others too.

Thanks and Regards,
Suraj Tripathi
 
Anime LoverAnime Lover
for(Account acc : [select Id,name,Industry from Account where Id ='0012i00000cPzwg']){
    String condition = 'acc.Industry == \'Energy\'';
    System.debug('-> '+Boolean.valueOf(condition));
}

I have set above account Industry value to Energy but I am always getting FALSE value to my debug state ment
Anime LoverAnime Lover
Hi  Ankaiah  
usually, we use any Boolean expression in the if(Condition)  like If(Acc.Industry == 'Software') but can we put the condition into the string variable and use that variable to IF() condition like

String expression1 = 'Acc.Industry == 'Software';
if(expression1){
System.debug(true);
}