Apex: Booleans can be null

Apex on Salesforce is a subset of Java. In general a Java developer should feel right at home when creating Apex.

One of the things I encountered recently where Java and Apex differ is the ability to access Primitives. For example, Java has a boolean type, which can be true or false. Additionally, there’s a Boolean type, which can be true, false, or null, and can be used in Collections because it inherits from Object. If using the latter, the consumer need always check for null before checking true or false.

Apex does not have access to Primitive Data Types, only those which inherit from Object. Therefore this issue can result:

Boolean isError;
if (isError) {
  System.debug('Error!');
}

This will fail with:

System.NullPointerException: Attempt to de-reference a null object

Unless you instantiated the Boolean to a true/false, you must check for null before checking whether it’s true or false. Alternatively, you can explicitly check for true (which feels wrong, but would circumvent the issue):

Boolean isError;
if (isError == true) {
  System.debug('Error!');
}

No issue results.

I saw this recently when I queried a Checkbox field on an object. I created the Checkbox field AFTER the record was created, so each of the existing records default the Checkbox (Boolean) field to null, instead of false as you might expect.

In summary:
The Best Practice for dealing with Booleans in Apex is to explicitly check for == true/false

if (Boolean == true)

rather than use the shorthand.

if (Boolean)

Hat tip to Jeegar Brahmakshatriya for the help.

This entry was tagged . Bookmark the permalink.