Search code examples
javaif-statementlinked-listnullpointerexception

How can I only refer to an object ONLY if it actually exists?


I am implementing a stack using linked list in java. The problem is that I get a nullPointerException when there is no element below, e.g. the StackNode.link does not exist. Therefore if I try assigning the StackNode.link I get the Exception.

Using an if statement to only run the code if it exists, I just get the Exception in the if statement. How do I go about this?

int pop() {

    StackNode temp = top;

    // update top
    top = belowTop;
    belowTop = top.link; // this is where I get the nullPointExcpetion


    return temp.data;

}

I would expect that when top.link does not exist (e.g. is null) then belowTop would just be null. This would be fine, but as described I get the exception.

EDIT: This is what I tried with the if-statement

if (top.link != null) {
        belowTop = top.link;
    }
else {
        belowTop = null;
    }

Solution

  • You need to check if the variable top has been initialized or not:

    ...
    if (top != null) {
       belowTop = top.link;
    } else {
       // Handle the not initialized top variable
    }
    ...
    

    Probably a good solution is to throw a runtime exception if belowTop if not initialized, like

    ...
    if (top == null) {
       throw new IllegalStateException("Can't pop from an empty stack");
    } 
    belowTop = top.link;
    ...
    

    In this case you have to prepare also a method that gives the ability to check if the stack is not empty or not initialized. Here a complete proposal:

    public boolean isEmpty() {
       // Your logic here 
    }
    
    // Better have a public access because it seems an utility library and 
    // it should be accessed from anywhere
    public int pop() {
    
        StackNode temp = top;
    
        // update top
        top = belowTop;
        if (top == null) {
            throw new IllegalStateException("Can't pop from an empty stack");
        } 
        belowTop = top.link; // Now it works
    
        return temp.data;
    
    }
    

    And you can use it as follow:

    if (!myStack.isEmpty()) {
       int value = myStack.pop();
       // Do something
    }