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?
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());
// ...
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