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.
static ... dataisn't initialized in 1st case, so it got defaultnullvalue, and you get an NPE..or a[after a variable not properly set.void addItemexpects aList<Object>, but instead it gets a null pointer, namelydatawhich has not been initialized so it is null. In the second snippet it gets an initialized vector. What is the confusion?