Jeffery
Jeffery

Reputation: 134

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?

Upvotes: 1

Views: 2341

Answers (2)

Jason
Jason

Reputation: 11822

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.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

head is supposed to be a Node type object here

This is optional. Java allows head to be a Node object, or null, to indicate that head is not referencing any nodes at all.

The value of null is special in Java. It is allowed to go wherever an object can go. It indicates that the variable to which you assign null is empty. This is perfectly fine, assuming that the rest of your program deals with null checking.

Upvotes: 1

Related Questions