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.

4
  • 1
    static ... data isn't initialized in 1st case, so it got default null value, and you get an NPE. Commented Apr 3, 2015 at 19:50
  • Because stackoverflow.com/questions/40480/… Commented Apr 3, 2015 at 19:50
  • NullPointerException - look for a . or a [ after a variable not properly set. Commented Apr 3, 2015 at 19:54
  • In the first snippet the method void addItem expects a List<Object>, 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? Commented Apr 3, 2015 at 21:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.