Wednesday, 19 April 2017

java - Data Structure in array NullPointerException





Possible Duplicate:
NullPointerException when Creating an array of object







I am having NullPointerException in main method, in line



array[0].name = "blue"; 


Structure Class:



public class Items {


String name = "";
String disc = "";
}


Main Class :



public class ItemsTest {


public static void main(String[] args) {
// TODO Auto-generated method stub

Items[] array = new Items[2];

array[0].name = "blue"; //NullPointerException
array[0].disc = "make";
array[1].name = "blue";
array[1].disc = "blue";
}

}


Please help me how to resolve this.


Answer



Items[] array = new Items[2];


You have to initialize each element of array, by default they are null




Make it,



Items[] array = new Items[2];
//initialization
array[0] = new Items();
array[0].name = "blue"; //NullPointerException
array[0].disc = "make";

//initialization
array[1] = new Items();

array[1].name = "blue";
array[1].disc = "blue";

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...