Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean if condtion [duplicate]

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?");
 }
like image 481
Rajkumar Seenappa Avatar asked Jan 31 '26 21:01

Rajkumar Seenappa


1 Answers

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.

like image 173
Kedar Mhaswade Avatar answered Feb 03 '26 11:02

Kedar Mhaswade