Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java if Statement gives me a NullPointerException in an if statement

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())
)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading