Pitfall of Auto-Unboxing Null Objects into Primitives
suggest changepublic class Foobar {
public static void main(String[] args) {
// example:
Boolean ignore = null;
if (ignore == false) {
System.out.println("Do not ignore!");
}
}
}
The pitfall here is that null is compared to false. Since we’re comparing a primitive boolean against a Boolean, Java attempts to unbox the Boolean object into a primitive equivalent, ready for comparison. However, since that value is null, a NullPointerException is thrown.
A primitive cannot be compared with null. The condition false == null is a compile-time error: incomparable types: boolean and <null>.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents