Convert String to Boolean in Salesforce Apex

Recently, I fixed a bug in a custom Salesforce Application where users had the option to turn off/on notifications. The preferences are stored as strings in a custom field on a User_Preference__c object. The possible values for this field are “true” or “false.”

I had to convert these string values to Boolean values for the Apex code for conditional logic. To solve this, I used an Apex method that reads the user preference string, converts it to a Boolean, and then uses it to determine whether to send a notification.

In this Salesforce tutorial, I will explain how to convert a string to a boolean in a Salesforce Apex Class.

Convert String to Boolean in Salesforce Apex

To convert a String data type to a Boolean, navigate to your Salesforce developer console and follow the steps below.

  1. In the developer console, create a new class by selecting File > New > Apex Class.
  1. Enter the new class’s name and click the OK button.
  1. Enter the code below in the developer console and save it.
public class ConvertStringToBoolean {
    public static Boolean convertStringToBoolean(String str) {
        Boolean result;
        
        if (String.isEmpty(str)) {
            result = false; 
        } else {
            result = Boolean.valueOf(str);
        }
        return result;
    }
}
  1. After entering the code, if there are no errors in the apex code, execute it using the shortcut keys “Ctrl+E.”
  1. We will test the apex code for boolean and non-boolean values in the anonymous window, and for that, enter the code below.
String strTrue = 'true';
String strFalse = 'false';
String strInvalid = 'notaboolean';

Boolean boolTrue = ConvertStringToBoolean.convertStringToBoolean(strTrue);
Boolean boolFalse = ConvertStringToBoolean.convertStringToBoolean(strFalse);
Boolean boolInvalid = ConvertStringToBoolean.convertStringToBoolean(strInvalid);

System.debug('True String Converted to Boolean: ' + boolTrue);  
System.debug('False String Converted to Boolean: ' + boolFalse);   
System.debug('Invalid String Converted to Boolean: ' + boolInvalid); 
  1. In the Console log window, select the checkbox Debug only, then you will see the output of the three values we have entered.

Here, in the output, we got True for the True string, False for the False string, and for the invalid string, we also got False as output.

Convert String to Boolean in Salesforce Apex

By following the above steps, you can convert a string data type to a Boolean in Salesforce Apex.

Illegal conversion from String to Boolean in Salesforce Apex

In Salesforce Apex, you get an “Illegal Assignment” error while converting a string value to a boolean. This error occurs while compiling the code because Apex is a strongly typed language that checks a variable’s data type during compile time.

In Salesforce, the apex conversion of a data type should be valid; otherwise, the