panda
panda

Reputation: 3

null pointer exception

public class Main {
public static void main(String args[]) {

List list = new List(0);

int[] intArr = null;  
list.fillWithRandom(intArr); // null pointer
list.print(intArr);
   }
 }



  import java.util.*;
  class List {


 private static final int NUMINTS = 10;



 private void list(int numInts) {
 List list = new List(10); 
 int[] intArr = new int[10];
 } 

public List(int i) {
// TODO Auto-generated constructor stub
 }


//fill array with random numbers
 public void fillWithRandom(int intArr[]) {
 Random r;
 r = new Random();

 int i;

 for(i=0; i < NUMINTS ; i++)

 intArr[i] = r.nextInt();     // null pointer
} 

 //display numbers
public void print(int intArr[]) {
int i;
for(i=0 ; i < NUMINTS; i++)
System.out.println(intArr[i]);


    }
  }

My message in the compiler says:

Exception in thread "main" java.lang.NullPointerException at List.fillWithRandom(List.java:28) at Main.main(Main.java:9)

Upvotes: 0

Views: 708

Answers (3)

paxdiablo
paxdiablo

Reputation: 881443

You set your int array to null, then pass it to fillWithRandom. Then, without actually allocating any space for that array, you attempt to populate it.

You need to allocate memory before you can use it.


Here's a nice simple one to start with:

test.java:

    public class test {
        public static void main(String args[]) {
            MyList list = new MyList(10);
            list.fillWithRandom();
            list.print();
        }
    }

MyList.java:

    import java.util.Random;

    public class MyList {
        private int[] list = null;

        public MyList(int numInts) {
            list = new int[numInts];
        }

        public void fillWithRandom() {
            Random r = new Random();
            for (int i=0; i < list.length; i++)
                list[i] = r.nextInt();
        }

        public void print() {
            for (int i=0 ; i < list.length; i++)
                System.out.println(list[i]);
        }
    }

Upvotes: 4

panda
panda

Reputation: 3

  class Main {
private static Object intArr;

public static void main(String[] args) {

    List list = new List(10);
    list.fillWithRandom(intArr);
list.print(intArr);

}
  }




   import java.util.Random;
 public class List {

 private int[] list = null;

 public List(int numInts) {
 list = new int[numInts];
 }

 public void fillWithRandom(Object intArr) {
     Random r = new Random();
     for(int i = 0; i < list.length; i++)
         list[i] = r.nextInt();

 }
 public void print(Object intArr) {
     for(int i=0; i <list.length; i++)
     System.out.println(list[i]);
 }


   }

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

You passed in a null array intArr to method fillWithRandom.

Upvotes: 0

Related Questions