Consider this class:
public class TestMap extends HashMap<String, Float> {
public static void main(String[] args) {
TestMap tm = new TestMap();
tm.put("A", 0F);
tm.put("B", null);
String[] keys = new String[]{"A", "B"};
for (String key : keys) {
System.out.println(key);
Float foo = (tm == null ? 0F : tm.get(key));
// Float foo = tm.get(key);
System.out.println(foo);
}
}
}
A NullPointerException is produced on the line Float foo =...
during the second iteration of the loop:
A
0.0
B
Exception in thread "main" java.lang.NullPointerException
at TestMap.main(TestMap.java:14)
If I replace the existing line with the commented line immediately below it works as expected, assigning foo = null. Why is the behavior different in these two cases?