0

I have the following simple code

Boolean b = null;
if(b){....}

It is throwing a NPE. Do you know what are the JVM/JDK mechanisms that trigger this NPE instead of just returning false ? I must say I did not looked at the bytecode.

greg
  • 306
  • 1
  • 13

2 Answers2

2
Boolean b = null;
if(b){....}

This condition will require an unboxing of the Boolean to get a boolean.

if(b.booleanValue() == true)

It is basically using Boolean.booleanValue giving the NullPointerException.

You can prevent this using

Boolean b = null;
if(Boolean.TRUE.equals(b)){ //NPE safe
    System.out.println(bool);
}

But this is a bit more verbose.

Careful, you don't have 2 states (true/false) but 3 (true/false/null) so you can have something like

if(Boolean.TRUE.equals(b)){ 
    System.out.println("true);
} else if(Boolean.FALSE.equals(b)){
    System.out.println("false");
} else {
    System.out.println("null");
}

You can also use Optional.
A quick and dirty example :

Optional.ofNullable(b).ifPresent(bool -> {
    System.out.println(bool);
});
AxelH
  • 14,325
  • 2
  • 25
  • 55
1

An if statement expects a boolean. A boolean can only be true or false, no null allowed since it is a primitive data type and not an Object.

But then there is auto-boxing. It's a technique where Java automatically converts primitives into their wrapper objects, so

boolean <-> Boolean
int     <-> Integer
double  <-> Double
...

whenever needed.

Since those wrapper objects are Objects, null is a possible value for them. So if you write

Boolean b = null;
if (b) { ... }

Java knows you are passing a Boolean object and tries to unwrap it automatically into its boolean representation. Therefore, it calls the method Boolean#booleanValue (documentation). So your code gets converted to something like

if (b.booleanValue()) { ... }

When evaluating this statement you are trying to call a method on something that is null. This is not possible and correctly throws a NullPointerException.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82