E
E
Eugene2014-07-06 12:03:43
Java
Eugene, 2014-07-06 12:03:43

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));
    }
  }
}

It compiles all the rules.
java A
Actually the question is, why do I get this output when I run the class without arguments ?
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)

PS I know how to fix the error, but I don't understand why it occurs? Enlighten me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Pavlov, 2014-07-06
@zolt85

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 question

Ask a Question

731 491 924 answers to any question