Answer the question
In order to leave comments, you need to log in
Why is NullPointerException thrown?
Hello.
There is this class:
import java.lang.*;
import java.util.*;
public class A {
public static void main(String[] args){
List<Object> list = makeList(args);
operationWithList1(list);
operationWithList2(list);
System.exit(0);
}
private static List<Object> makeList(String[] args) {
System.out.println("init list if args is not empty");
if(args.length > 0) {
return new ArrayList<Object>();
}
return null;
}
private static void operationWithList1(List<Object> list) {
System.out.println("operationWithList1 ...");
if(list == null){
list = new ArrayList<Object>();
}
list.add(1);
list.add(2);
System.out.println("list is exists!");
for(int i = 0; i < list.size(); i++) {
System.out.println("\tlist item[" + i + "] = " + list.get(i));
}
}
private static void operationWithList2(List<Object> list) {
System.out.println("operationWithList2 ...");
for(int i = 0; i < list.size(); i++) {
System.out.println("\tlist item[" + i + "] = " + list.get(i));
}
}
}
java A
init list if args is not empty
operationWithList1 ...
list is exists!
list item[0] = 1
list item[1] = 2
operationWithList2 ...
Exception in thread "main" java.lang.NullPointerException
at A.operationWithList2(A.java:37)
at A.main(A.java:10)
Answer the question
In order to leave comments, you need to log in
In Java, data is passed to methods by value . So after the call , the
list declared in main remains null .
Passing Reference Data Type Arguments
Is Java “pass-by-reference” or “pass-by-value”?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question