4

I have a very basic method as a part of a binary search tree which simply returns True if the current binary node has a right child or False if that right child points to null.

public boolean hasRight(){
    if(right.element != null){
        return true;
    }else{
        return false;
    }

However whenever I test this code, the moment that I know I will reach a node that does not have a right child, and would expect my code to just return False, java throws a NullPointerException at the line

    if(right.element != null)

instead of returning False like I would expect it to.

Edit:

Fixed my code, simply had to check right itself being null before trying to get the element of right

public boolean hasRight(){
    if(right != null){
        return true;
    }else{
        return false;
    }
}
1
  • 2
    What does it display when you do if (right == null) {...} ? Commented Mar 18, 2014 at 15:54

3 Answers 3

10

Then right itself is null. Check for that first before attempting to access something on it.

if (right != null && right.element != null){
Sign up to request clarification or add additional context in comments.

Comments

5

if right is null, you cannot access right.element().

btw: Your method can be easier written as

hasRight(){
   return right != null;
}

Comments

3

If you are getting a NullPointerException, then right should be null. So you could do this:

if(right != null && right.element != null){
    return true;
}else{
    return false;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.