0

I've got the following if statement, where parent, grandparent, and child are all objects. For some reason, this if throws a NullPointerError when it comes to the parent.isRightChild() check. If this where an issue with the isRightChild() function, I would've caught it fairly easily, but it isn't. This just baffles me, because there should be no way for parent to be null. Thanks in advance.

if (parent != null && grandparent != null
    && (parent.isLeftChild() && child.isRightChild())
    || (parent.isRightChild() && child.isLeftChild())
)

1 Answer 1

3

When parent and child objects are null and if condition is trying to access the parent.isRightChild() method. So it is throwing the NullPointerException.

if (parent != null && grandparent != null
    && (
          (parent.isLeftChild() && child.isRightChild())
         || (parent.isRightChild() && child.isLeftChild())
      )
)

group the method accessing conditions as separate(as shown above), so it will not reach those conditions if objects are null.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.