Jeffery Jeffery - 1 month ago 6
Java Question

Why we can use Node head = null without instantiate the 'head' in Java?

I am reading someone's code. It is about getting input numbers and convert those number into a Linked list. The part of the code is like this:

class Node {
int value;
Node next;
Node() {
next = null;
}
}


Firstly We need to create a
head
node to indicate head and we let the
head
be null like this
Node head = null
.

My limited experiences of java tell me that
head
is supposed to be a Node type object here. So why we can use
Node head = null
without instantiate the
head
?

I think at least I should create
Node head = new Node()
; then we can use
Node head = null
;

Anyone can explain it to me?

Answer
Node head = null;

This line states that there are no items in the linked list. This is valid in Java and indicates that although head can contain a Node object (or an object of a derived class), it is currently empty.

To add an item to the list, there is likely some code such as:

public void addItemToLinkedList(int value) {
    if (head == null) {
        head = new Node();
        head.value = value;
    } else {
        ...
    }
}

So if there is no first Node (when head equals null) then head is created. Otherwise if head already exists, the else block would execute which would look for the end of the list and add another Node.