28

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.

xan
  • 7,511
  • 2
  • 32
  • 45
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • 5
    Well, he included the line the exception was thrown. I don't think the NullPointerException stacktrace is helpful in this case, besides for pointing the line – notnoop Nov 28 '09 at 13:50
  • See also *[What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384)*. – Peter Mortensen May 09 '19 at 12:15

3 Answers3

74

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.

notnoop
  • 58,763
  • 21
  • 123
  • 144
  • it's exactly that, find more about autoboxing/unboxing here: https://www.geeksforgeeks.org/autoboxing-unboxing-java/ – Panos K. Nov 01 '19 at 07:01
4

Check for inverse.containsKey(animal), BiMap<PhylogenyTree, Integer>. The inverse might not have the animal.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Summy
  • 807
  • 6
  • 5
-1

You must have a stacktrace. It says exactly what was the line where that happened. Post it and we can tell.

From all the posted code, I can "guess" one of these are a potential NullPointerException (NPE).

node may be null and calling node.getParent.

The node's parent may be null and invoking parent.getChildren may throw an NPE.

One of the siblings may be null and invoking sibling.equals may throw an NPE.

cellInfo may be null and cellInfo.inverse will throw it.

Finally the "inverse" returned may be null and inverse.get() will throw it.

Phew!!...

So, to avoid doing this wild guessings, why don't you just post your stacktrace and we find out?

It should something like:

 java.lang.NullPointerException: null
 at YourClass.setSiblings( YouClass.java:22 )
 at YourClass.setSiblng( YourClass.java: XX )

etc.. .

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
OscarRyz
  • 196,001
  • 113
  • 385
  • 569