The other day I saw a question on a forum in which it was noted that the following Apex code fails with a null exception error:

Boolean testVal = null;
if ( testVal )
System.debug( ‘Testval is true.’ );
System.debug( ‘Testval is false.’ );

This is somewhat unexpected in that in almost every other language, a null value in a Boolean variable is considered False.

In Apex, primitive variables always support a null value in addition to their expected values. Thus if you enter the following code into the developer console:

Integer i;
Boolean b;
Date d;
DateTime dt;
Decimal dl;
Double dbl;
Long l;
String s;
Time t;

You’ll see that they all come out as true. And if you try to access any method on the object, you’ll get a null reference exception.

Boolean variables in Apex are thus consistent with other primitive data types.

Where it gets interesting is when you look at how you might use a Boolean value in code.

Let’s say you have an uninitialized Boolean variable b;

if(b) … will fail with a null reference exception

if(!b)… will fail with a null reference exception

Fair enough, but now consider the following two statements:

Boolean b;
if(b!=true) system.debug(‘b is not true’);
if(b!=false) system.debug(‘b is not false’);

The result will be:

b is not true
b is not false

Well now, everyone knows that a real Boolean variable can’t be ‘not true’ (which is false) and ‘not false’ (which is true) at the same time.

Which means, to put it bluntly, that a Boolean variable in Apex is not really a true Boolean variable – at least as far as purists would be concerned.

Fortunately, I’m not much of a purist, so the real concern is what this means in practice.

First – always initialize your variables! This is especially true for those of you coming from .NET, which kindly initializes value type variables for you.

Second, test for null values where appropriate, even if you are using primitive data types.

Third, the safest comparison for Booleans is always against true – i.e. b == true or b != true. if you do this consistently, any null values that do sneak in will be treated as false. But does this mean you should always compare Booleans against True? Not necessarily – because you might want to catch those null reference exceptions to detect uninitialized variables or failures to check against null values.

It does mean you should never compare against false –
because in Apex b!= false doesn’t mean b is always true.