0

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.

Damien-Amen
  • 7,232
  • 12
  • 46
  • 75
  • 1
    `static ... data` isn't initialized in 1st case, so it got default `null` value, and you get an NPE. – Victor Sorokin Apr 03 '15 at 19:50
  • Because http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – chancea Apr 03 '15 at 19:50
  • NullPointerException - look for a `.` or a `[` after a variable not properly set. – Thorbjørn Ravn Andersen Apr 03 '15 at 19:54
  • In the first snippet the method `void addItem` expects a `List`, but instead it gets a null pointer, namely `data` which has not been initialized so it is null. In the second snippet it gets an initialized vector. What is the confusion? – aestrivex Apr 03 '15 at 21:25

1 Answers1

1

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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525