- Salesforce Development Posts of a Fashion by Matt Lacey

Back to Posts

Playing With Primitives

A large part of being a software developer is knowing the ins and outs of the platform that you're working with, including it it's quirks, it's APIs and the languages available to you; needless to say, this can amount to a vast amount of information, and it's all too easy to forget some of the simple things from time to time.

One of my colleagues turned to me recently and asked if a boolean variable in Apex can be null or not, and all I could answer him with was a blank face while I tried in vain to remember whether it was possible.

Booleans: Not Binary

Booleans are, as per the documentation, a primitive data type in Apex and as you should know this means that they're passed by value, not by reference (as would be with an instance of a custom class or SObject), but you can indeed assign null to primitive variables. In fact, the documentation clearly states that primitives are initialised to null, and as such you should always initialise variables with an appropriate value.

All Apex variables, whether they’re class member variables or method variables, are initialized to null. Make sure that you initialize your variables to appropriate values before using them. For example, initialize a Boolean variable to false.

Depending on your background you may or may not find this surprising; for instance a C++ developer would not expect to have a problem if they assign NULL to a bool variable, but they're likely to be aware that NULL is defined as 0 or (void *)0, and a value of 0 is false, so the bool-type variable will be false.

#include <stdio.h>
int main(int argc, char ** argv)
  // This will print 'Hello, World!' to the standard output
  bool b = NULL;
  if(!b) printf("Hello, World!\n");
  return 0;


In Apex, assigning null to a Boolean variable gives it the value null, it is neither true or false, and if you try to test it as such you'll end up on the wrong end of null-dereference exception—an outcome that is unlikely to be desirable.

/* Since b isn't initialised explicitly 'if(b)'
  will throw an exception! */
Boolean b;


Something that does surprise me (though it probably shouldn't) is that you can also assign null to a boolean variable yourself, with the same effect as in the code above. For some reason I expected a compiler error might surface when trying to do such an assignment, but the documentation does show that the boolean type can in take the values true, false and null, so beware: always intialise your variables, and if you do choose to assign null to a boolean, be sure that it's assigned a truth value again before trying to test it!

Related Posts