Jeffery Jeffery - 1 year ago 63
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
node to indicate head and we let the
be null like this
Node head = null

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

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 Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download