Damien-Amen
Damien-Amen

Reputation: 7492

Why does this throw Null Pointer Exception?

My code :

static List<Object> data;
private void addItem(List<Object> list) {
    try {
        data = new ArrayList<Object>();
        list.add("test");
    } catch (Exception e) {
        e.printStackTrace();        
    }
}

public static void main(String[] args) {
    ListTest test = new ListTest();
    test.addItem(data);
}

Above code throws NullPointerException. The code below does not throw NPE.

static List<Object> data = new Vector<Object>();
private void addItem(List<Object> list) {
    try {
        list.add("test");
    } catch (Exception e) {
        e.printStackTrace();        
    }
}

public static void main(String[] args) {
    ListTest test = new ListTest();
    test.addItem(data);
}

Above code does not throw NullPointerException. I don't understand the difference between both.

Upvotes: 0

Views: 73

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213213

Even though you passed data reference to the method, the moment you assign a new list to data:

data = new ArrayList<Object>();

list and data reference are now pointing to 2 different objects. Before that assignment, data was set to null and so was list. But after the assignment, only list is set to null. And thus calling list.add() will result in NPE.

In second case, data was not null to begin with.

Upvotes: 1

Related Questions