I declare a Boolean variable. For example Boolean dataVal=null;
Now if I execute the following code segment:
if(dataVal)
System.out.println("\n\NULL value in dataVal: "+dataVal);
else
System.out.println("\n\nvalue in dataVal: "+dataVal);
I get NullPointerException. Well, I know its obvious, but I need to know the reason behind this.
When you evaluate the boolean value of a
Booleanobject Java unbox the value (autoboxing feature, since 1.5). So the real code is:dataVal.booleanValue(). Then it throwsNullPointerException. With any boxed value, unboxing a null object throws this exception.Before 1.5 you had to unbox the value by hand:
if (dataVal.booleanValue())so it was more evident (more verbose too 🙂