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)
You set your
intarray to null, then pass it tofillWithRandom. 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:
MyList.java: