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;
}
链接地址: http://www.djcxy.com/p/76056.html

上一篇: 抛出Exception的哪个部分很贵?

下一篇: Java NullPointerException对条件空值检查