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.
An object of type Boolean contains a single field whose type is boolean . In addition, this class provides many methods for converting a boolean to a String and a String to a boolean , as well as other constants and methods useful when dealing with a boolean .
Boolean variables can either be True or False and are stored as 16-bit (2-byte) values. Boolean variables are displayed as either True or False. Like C, when other numeric data types are converted to Boolean values then a 0 becomes False and any other values become True.
A boolean variable in Java can be created using the boolean keyword. Unlike C++, a numerical value cannot be assigned to a boolean variable in Java – only true or false can be used. The strings “true” or “false” are displayed on the console when a boolean variable is printed.
In Java, a boolean is a literal true or false , while Boolean is an object wrapper for a boolean . There is seldom a reason to use a Boolean over a boolean except in cases when an object reference is required, such as in a List .
When you evaluate the boolean value of a Boolean
object Java unbox the value (autoboxing feature, since 1.5). So the real code is: dataVal.booleanValue()
. Then it throws NullPointerException
. 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 :)
Because dataVal
is being casted to boolean
using Boolean.booleanValue()
which gets translated to null.booleanValue()
which leads you to a NullPointerException.
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