Ângelo
Ângelo

Reputation: 81

Access class and create objects

i'm trying to access a class named "Person" which has only one argument, "name" here's my class:

class person{
  String name;
   public void setName(String name){ this.name = name; }
   public String getName(){ return name; }
  }

And then on my main class i've got the following:

public class exercise{
   public static void main(String []args){
   Person person [] = new Person [20];
   person[0].setName("zgur");
   System.out.printf(""+person[0].getName());
  }
}

I'm getting the error: Exception in thread "main" java.lang.NullPointerException

What am i missing and/or doing wrong?

Thanks.

Upvotes: 1

Views: 50

Answers (3)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're creating an array but not filling it with objects. Think of an array of reference type like an egg crate. Until you fill it with eggs, you can't use any of the eggs in the crate.

So change to:

// note that class names should begin with an uppercase letter
public class Exercise{
   public static void main(String []args){
     Person[] people = new Person [20];
     for (int i = 0; i < people.length; i++) {
       people[i] = new Person();       }
     people[0].setName("zgur");
     System.out.printf("" + people[0].getName());
   }
}

If this were my code, I'd consider using an ArrayList<Person> and only add a Person if and when needed. For example

public static void main(String[] args) {
  List<Person> personList = new ArrayList<Person>();
  personList.add(new Person("Stan"));  // assuming that a String constructor exists
  personList.add(new Person("Bill"));
}

Upvotes: 2

Alan
Alan

Reputation: 822

You need the following:

Person[] people = new Person[20];
people[0] = new Person("Harry");
people[1] = new Person("Alan");
...etc.

Upvotes: 2

Sergey
Sergey

Reputation: 21

Please note that here you don't create a Person instance:

Person person [] = new Person [20];

Here you create an array of 20 references, but every reference is initialized with null. So accessing zeroe's element as

person[0].setName("zgur");

you are getting the NPE.

If you really need to use an array to work with your Person instances, ensure that you have initialized the item you're addressing:

person[0] = new Person();

person[0].setName("whateverYouNeed");

Just a little note: it's preferable to use the followed form of array creation:

Person[] person = new Person[20];

with [] after the reference type.

Upvotes: 2

Related Questions