Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: null pointer exception when unboxing Integer?

Tags:

This code is causing a null pointer exception. I have no idea why:

private void setSiblings(PhylogenyTree node, Color color) throws InvalidCellNumberException {     PhylogenyTree parent = node.getParent();      for (PhylogenyTree sibling : parent.getChildren()) {         if (! sibling.equals(node)) {             Animal animal = sibling.getAnimal();             BiMap<PhylogenyTree, Integer> inverse = cellInfo.inverse();             int cell = inverse.get(animal); // null pointer exception here             setCellColor(cell, color);         }     } } 

I've examined it in the debugger, and all the local variables are non-null. How else could this be happening? The BiMap is from Google Collections.

like image 977
Nick Heiner Avatar asked Nov 28 '09 05:11

Nick Heiner


People also ask

How do I fix NullPointerException in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

Can NullPointerException be caught in Java?

The java. lang. NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null. Since the NullPointerException is a runtime exception, it doesn't need to be caught and handled explicitly in application code.

Can NullPointerException be caught by exception?

It is generally a bad practice to catch NullPointerException. Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem.

Can NullPointerException be extended?

Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException .


1 Answers

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.

like image 114
notnoop Avatar answered Oct 26 '22 20:10

notnoop