0

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.

Community
  • 1
  • 1

3 Answers3

2
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";
jmj
  • 237,923
  • 42
  • 401
  • 438
1

When you wrote the line:

Items[] array = new Items[2];

You initialized an Array of the type Items which can contain 2 elements, or in other words, you only initialized the container.

Each element in the array is an object and also needs initialization, and when addressing array[0].name you're trying to access the inner element which is currently null If you'll check Jigar Joshi answer, you'll see he also initializes each Items element inside the array.

Hope this helps!

Community
  • 1
  • 1
Meny Issakov
  • 1,400
  • 1
  • 14
  • 30
0
Items[] array = new Items[2]; // Creates an array of Items with null values

Hence have to use

Items[] array = { new Items(), new Items() }; // as suggested by aioobe....

or need to intialise the array like

array[0] = new Items();
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
kartheek
  • 320
  • 1
  • 4
  • 9