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.

2

3 Answers 3

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";
Sign up to request clarification or add additional context in comments.

Comments

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!

Comments

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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.