Rajkumar Seenappa Rajkumar Seenappa - 6 months ago 13
Java Question

Boolean if condtion

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?");
}

Answer

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.

Comments