Yoink
Yoink

Reputation: 197

Java NullPointerException on conditional null check

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;
    }
}

Upvotes: 4

Views: 253

Answers (3)

Christian Tapia
Christian Tapia

Reputation: 34146

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;
}

Upvotes: 3

dognose
dognose

Reputation: 20889

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

btw: Your method can be easier written as

hasRight(){
   return right != null;
}

Upvotes: 5

rgettman
rgettman

Reputation: 178243

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

if (right != null && right.element != null){

Upvotes: 10

Related Questions