This is Element
class:
public class Element {
private String elementName;
private int atomicNumber;
private String Symbol;
priv
Creating new object arrays will yield arrays filled with null
. If you need to have objects, you will have to iterate over the array after its creation and populate it with new instances.
Declaring an array like initialises the array object, but not the elements of the array. You need to create an Element object at each index of the array.
element[0] = new Element();
element[0].setElementName("H");
You have not initialized element[0]
. You need to initialize it first, in fact every array element if you intent to use them.
element[0]=new Element();
or you can initialize all of them using loop
for(int i=0;i<element.length;i++)
{
element[i]=new Element();
}
Between those two lines
Element[] element = new Element[103];
element[0].setElementName("H");
you need to create element[0]
, that is to build a new instance of Element
. In your code element[0]
is null, hence the NullPointerException
when you call setElementName
.
The Problem is in the part:
Element[] element = new Element[103];
element[0].setElementName("H");
Your accessing the first element without creating it before that. you create the array but it doesnt containt automatically new objects of the type used, you have to declare these explicitly, for example:
element[0] = new element();
And then you can use the object.
You need to create objects. You just created array of object references.
Element[] element = new Element[103];
for(int i=0; i<103; i++) {
element[i] = new Element();
}
As your element is object (arrays are object) and it is stored on heap. All Element object references are initialized to null value. Due to which you are getting NPE
s.
Element[] element = new Element[103];
element[0].setElementName("H"); // element[0] is null