Search code examples
javadummy-variable

Dummy head declaration


Dummy is used to record where the initial head is. why do we have to set up dummy head as Node dummy = new Node(0) but not Node dummy = null. (I get NPE for doing so). Don't we just need to return the head position? Why does setting up dummy with a value mater?


Solution

  • It all comes down to what "null" is in java, and what it means to "instantiate" an object. When you setup the dummy head as:

    Node dummy = new Node(0);
    

    You are instantiating a new Node object, which is allocated in heap space, the reference to which is passed into the "dummy" variable.

    When you setup a dummy head like:

    Node dummy = null;
    

    You are not instantiating a new Node object, therefore there is no new object added to heap. Without a new object actually being created, by definition, there is no way to reference that. That is what null is, basically it means an empty reference, or a reference to something that doesn't exist (same thing). Because it has not been instantiated, when you try to reference it's fields you are going to get a NullPointerException.

    Per documentation (linked below) a null pointer exception is thrown when:

    • Calling the instance method of a null object
    • Accessing or modifying the fields of a null object
    • Taking the length of null as if it were an array
    • Accessing or modifying the slots of null as if it were an array
    • Throwing null as if it were a throwable value

    You didn't post the code that actually caused the NPE, but I imagine it is one of the top two reasons in the list above.

    https://docs.oracle.com/javase/7/docs/api/java/lang/NullPointerException.html