user3401592
user3401592

Reputation: 29

Null Pointer Exception at Array Class

Every time when I make a class and other class that will be an array where i will store the first class objects and i call a method ,i receive a nullPointerEception..

ex:

public class person {

    private String name,int age;
    public Class()//constructor

    public void print() {

        System.out.println(name);
        System.out.println(name);

        //.........others methods
    }
}

public class personList {

    person[] pl = new person[10];
    int i=0;

    public void add(person p) {

        pl[i]=p;
        i++
    }

    public void print() {

        for(int j=0;j<pl.length;j++)
        {
            pl[j].print();
        }
    }
}

The error is here: pl[j].print();

The object p[j] isn't null ,because I initiate in Main file(p=new person("Maxim",17),pl.add(p)).

Even if I intializate from Main like this p[0]=.....,p[1]=... I receive the same error.

What have I done wrong?

Upvotes: 0

Views: 73

Answers (2)

Thomas
Thomas

Reputation: 88707

person[] pl = new person[10]; will create an array of length 10 with all elements being null.

Thus, if you don't initialize all 10 elements your print() method will eventually throw a NullPointerException.

You seem to only call add(p) once, i.e. you only intialize element at index 0 to a non-null value and thus when j reaches value/index 1, person[j] will be null.

To fix this you should change your loop to for(int j=0;j<i;j++), assuming that print() is a method of class personList (your posts formatting makes it hard to determine).

A few side notes:

  • Please check the Java coding conventions and stick to them, since that will make it easier for others to read your code (and it will probably even help you). At least stick to the convention on class names which should be camel case and start with an upper case letter, e.g. PersonList not personList.

  • Instead of using an array and a counter, e.g. Person[] and i, it would be better to use a list or some other collection, e.g. List<Person>. That way the loop could become for( Person p : pl) { p.print() } and you'd also not be restricted to 10 elements.

Upvotes: 2

mttdbrd
mttdbrd

Reputation: 1831

The error is in this line:

person[] pl = new person[10];

You need to initialize each Person object in the array.

for(int i = 0; i < pl.length; i++)
{
    pl[i] = new Person();

}

Your constructor for Person is also wrong. It should be

public Person(){...}

not

public Class(){...}

Upvotes: 2

Related Questions