Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does unboxing work in short-circuited boolean expressions?

I recently tried to run the following two snippets of code and was surprised at the output.

First:

// ...
System.out.println( (Boolean)null || true );
// ...

Second:

// ...
System.out.println( (Boolean)null || false );
// ...

The first example results in the following output:
true

The second example results in the following output:
Exception in thread "main" java.lang.NullPointerException
   at com.blah.main(SanityCheck.java:26)

I would have thought both examples should result in a null pointer exception, as any short-circuiting is applied left-to-right. The attempt to unbox the boolean from the Boolean should have failed before the other side of the logical or was given consideration.

Can anyone explain this inconsistent behaviour?

like image 302
jr. Avatar asked Aug 23 '13 02:08

jr.


1 Answers

I ran the class file through JAD to see what the optimised code looked like. For the true case:

// ...
System.out.println(true);
// ...

For the false case:

// ...
System.out.println(null.booleanValue());
// ...
like image 195
jr. Avatar answered Sep 20 '22 03:09

jr.