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?
No comments:
Post a Comment