Java: null pointer exception when unboxing Integer?

The null pointer exception is a result of unboxing the result of inverse.get(animal). If inverse doesn’t contain the key animal, it returns null, “of type” Integer. Given that the assignment is to an int reference, Java unboxes the value into an int, resulting in a null pointer exception.

You should either check for inverse.containsKey(animal) or use Integer as the local variable type to avoid unboxing and act accordingly. The proper mechanism depends on your context.

Leave a Comment