class BooleanTester
{
boolean primitive;
Boolean object;
public static void main(String[] args) {
BooleanTester booleanTester = new BooleanTester();
System.out.println("primitive: " + booleanTester.getPrimitive());
System.out.println("object: " + booleanTester.getObject());
}
public boolean getPrimitive() {
return primitive;
}
public Boolean getObject() {
return object;
}
}
output:
primitive: false
object: null
This seems obvious but I had a situation where Jackson, while serializing an object to JSON, was throwing an NPE after calling a getter, just like this one, that returns a primitive boolean which was not assigned. This led me to believe that Jackson was receiving a null and trying to call a method on it, hence the NPE. I was wrong.
Moral of the story is that when Java allocates memory for a primitive, that memory has a value even if not initialized, which Java equates to false for a boolean. By contrast, when allocating memory for an uninitialized complex object like a Boolean, it allocates only space for a reference to that object, not the object itself - there is no object in memory to refer to - so resolving that reference results in null.
I think that strictly speaking, "defaults to false" is a little off the mark. I think Java does not allocate the memory and assign it a value of false until it is explicitly set; I think Java allocates the memory and whatever value that memory happens to have is the same as the value of 'false'. But for practical purpose they are the same thing.