NullPointerException when Creating an Array of objects

Viewed 60828

I have been trying to create an array of a class containing two values, but when I try to apply a value to the array I get a NullPointerException.

public class ResultList {
    public String name;
    public Object value;
}

public class Test {
    public static void main(String[] args){
        ResultList[] boll = new ResultList[5];
        boll[0].name = "iiii";
    }
}

Why am I getting this exception and how can I fix it?

9 Answers

You created the array but didn't put anything in it, so you have an array that contains 5 elements, all of which are null. You could add

boll[0] = new ResultList();

before the line where you set boll[0].name.

ResultList[] boll = new ResultList[5];

creates an array of size=5, but does not create the array elements.

You have to instantiate each element.

for(int i=0; i< boll.length;i++)
    boll[i] = new ResultList();

I think by calling

ResultList[] boll = new ResultList[5];

you created an array which can hold 5 ResultList, but you have to initialize boll[0] before you can set a value.

boll[0] = new ResultList();
class ResultList {
    public String name;
    public Object value;
    public ResultList() {}
}
 public class Test {
    public static void main(String[] args){
    ResultList[] boll = new ResultList[5];
    boll[0] = new ResultList(); //assign the ResultList objet to that index
    boll[0].name = "iiii";  
   System.out.println(boll[0].name);
   }
 }

Till you have created the ResultSet Object but every index is empty that is pointing to null reference that is the reason you are getting null. So just assign the Object on that index and then set the value.

Either you can try this scenario or you can the make the variable "name" static in ResultList Class. So when the ResultList[] boll = new ResultList[5]; gets executed at that time all the variable from that class will gets assign

public static void main(String[] args){
         ResultList[] boll = new ResultList[5];
    boll[0] = new ResultList();
    boll[0].name = "iiii";

    System.out.println(boll[0].name);
    }


public class ResultList {

    public  static String name;
    public  Object value;

    public ResultList() {}
}
Related