2

Following code snippet throws NullPointerException. I am trying to understand the workflow of if condition. If only true and false are valid parameters for the if condition, why does the Java compiler not throw an error?

 Boolean booleanFlag = null;

 if(booleanFlag) {
     System.out.println("Why this boolean flag code is executed?");
 }
Chris Martin
  • 30,334
  • 10
  • 78
  • 137

4 Answers4

6

This has to do with a feature of Java called auto(un)boxing. Basically, under the covers, the compiler translates this code to something like:

if (booleanFlag.booleanValue()) {
  //..

}

Now, if booleanFlag is null, then it throws an NPE at runtime. This is what Joshua Bloch means by "autoboxing blurs but does not erase the divide between primitive types and boxed equivalents".

Perhaps in this particular case of initialized boxed primitive compiler could at least generate a warning, but in general, generating such a warning is impossible.

Kedar Mhaswade
  • 4,535
  • 2
  • 25
  • 34
5

The Java compiler does provide errors based on any data flow analysis (beyond checking whether variables have been initialized, and in this case you've initialized it to null). It is entirely unaware that the value of booleanFlag is necessarily null at that point in the execution.

As for why, I can only speculate that the language authors knew a feature like that would add too much complexity to the language and too much performance cost to the compiler.

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
3

The java.lang.Boolean class wraps a value of the primitive type boolean in an object. An object of type Boolean contains a single field whose type is boolean.

Khan Abdulrehman
  • 816
  • 2
  • 10
  • 22
1

The Java language definition includes a concept of automatic "boxing" and "unboxing"

This allows primitive type (boolean, int, double etc) to be automatically converted to their Object equivalents (boxing) and for objects like Boolean, Integer etc to be converted to primitives (unboxing)

But unboxing requires that the object (eg Boolean) not be null. If it is null, then that is a runtime error (NullPointerException). It must be a runtime error, because the language does not provide enough information to consistently detect null conditions at compile time.

In your case, the compiler is attempting to unbox your Boolean booleanFlag into a boolean so that it can be used for an if condition, and that conversion is failing.

Tim
  • 6,406
  • 22
  • 34