Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean Object and boolean variable issue in JAVA

Tags:

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.

like image 200
riyana Avatar asked Feb 28 '12 09:02

riyana


People also ask

What is a boolean object in Java?

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 .

What is the difference between a Boolean variable and a boolean value?

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.

Can we use boolean as a variable in Java?

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.

What is difference between boolean and boolean in Java?

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 .


2 Answers

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 :)

like image 175
helios Avatar answered Sep 22 '22 12:09

helios


Because dataVal is being casted to boolean using Boolean.booleanValue() which gets translated to null.booleanValue() which leads you to a NullPointerException.

like image 20
Alex Avatar answered Sep 21 '22 12:09

Alex