How to check if the field value is empty in APEX?

Null checking is an important functionality in every programming language. In different languages, the null checking differs from the way the other language check null.

In this post, we are going to discuss the null checking in Salesforce APEX.

The following are some of the null checkings in APEX,

1. Boolean isBlank = record.txt_Field__c == '';
2. Boolean isBlank = record.txt_Field__c == null;
3. Boolean isBlank = record.txt_Field__c.trim() == '';
4. Boolean isBlank = record.txt_Field__c.size() == 0;
5. Boolean isBlank = record.num_Field__c = '';
6. Boolean isBlank = record.num_Field__c = null;
7. Boolean isBlank = record.lookup_Field__c = '';
8. Boolean isBlank = record.lookup_Field__c = null;

But which one is the better one to check null in each type of field,

  1. What is the best option for Text Field?

Instead of checking like below,

If( record.txt_Field__c == '' && record.txt_Field__c == null && record.txt_Field__c.trim() == '' && record.txt_Field__c.size() == 0) {
}

Apex does have a method called isBlank in the String class to return true if the specified String is white space, empty (‘’), or null, otherwise, it will return false. So simply we can check like below,

If( String.isBlank(record.txt_Field__c) {
}

There is another method called isEmpty available in the String class, but it will not check the whitespace as isBlank.

So the better option is to use String.isBlank(textField) for the String fields.

2. What is the best option for Numeric fields?

The better option for Numeric or the lookup field is just to check null, we don’t need to check the whitespace or empty (‘ ’) to find a numeric or lookup field empty or not.

If(record.Num_Field__c == null || record.Lookup_Field__c == null) {
}

References,

5 yrs of experience in Software Development and became a certified Salesforce Developer to develop end-to-end Salesforce features to Salesforce platform.