26

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.

arieljannai
  • 2,124
  • 3
  • 19
  • 39
riyana
  • 21,385
  • 10
  • 35
  • 34

7 Answers7

39

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

helios
  • 13,574
  • 2
  • 45
  • 55
16

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

Alex
  • 25,147
  • 6
  • 59
  • 55
5

You can have a look at the specification for unboxing issues, your situation is described here section 5.1.8 Unboxing Conversion : If r is null, unboxing conversion throws a NullPointerException

That means your if ( /* Boolean object */ ) will never be unboxed into a boolean primitive type and therefore throw a NPE because you are doing an invalid if(null).

By the way, unboxing will work if you had:

final Boolean booleanTest = new Boolean (true);
if (booleanTest) {
    // Do something
}
Jerome
  • 4,472
  • 4
  • 18
  • 18
1

Boolean (class) != boolean (primitive type).

Java tries to get the primitive value calling dataVal.booleanValue(). Because dataVal is null, you get a null pointer exception.

Pablo
  • 3,655
  • 2
  • 30
  • 44
0

When you try to evaluate Boolean object value jvm internally call booleanValue() on that object as you assign null to that object it will throw NullPointerException

Rakesh Bhagat
  • 397
  • 2
  • 5
  • 22
0

use BooleanUtils.tobolean(?), it returns false if the passed param is null

  • This doesn't answer the question at all - why exactly the NPE occurs. You answered the question how to prevent it, but the OP didn't ask this. – cyberbrain Apr 03 '22 at 18:34
0

if(null) is not a valid expression, simple as that.

Under the hoods, the VM is using auto-boxing... so you get a NullPointerException.

Marcelo
  • 4,580
  • 7
  • 29
  • 46