简体   繁体   中英

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

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

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

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

btw: Your method can be easier written as

hasRight(){
   return right != null;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM