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?");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With