Autoboxing and the NullPointerException Mystery
During one of the Java classes I teach, a student came up to me with a peculiar bug. Below is a simplified version:
HashMap<String,Boolean> map = new HashMap<String,Boolean>(); if (map.get("a") == true) // -> NullPointerException // do something
The NullPointerException here seems odd. While the == true
seemed superfluous, I initially thought this would work. Even if it didn't, I couldn't understand why this would give a NullPointerException.
A NullPointerException occurs when you try to use a reference that hasn't been initialized yet (its value is null), but the only reference used here is map
, which was definitely initialized!
I tried a few things:
System.out.println( map.get("a") ); // -> null
As I expected, this gave a null
.
Then I tried:
System.out.println( null == true ); // -> CompileError: Incomparable types: <null> and boolean
Ok, so I had forgotten that in Java, you can't compare two objects of different types. In some other languages, null
is considered "falsy".
But when I try:
System.out.println( map.get("a") == true ) // -> NullPointerException
Read full article from Autoboxing and the NullPointerException Mystery
No comments:
Post a Comment