0

I'm just stuck on error "Exception in thread "main" java.lang.NullPointerException" Please tell me the mistake I'm committing, with solution. its a simple array. How i can access the method setAge(int) from this array.

    Person arr[] = new Person[2];

    arr[0].setAge(20);

Thanks.

1
  • 1
    fill your array first.. Commented Mar 31, 2014 at 22:20

4 Answers 4

6

You are creating an array with two empty slots. Populate these slots first:

arr[0] = new Person();
arr[1] = new Person();

Or for a big array use a loop:

for(int personIndex = 0; personIndex < arr.size; personIndex++)
{
    arr[personIndex] = new Person();
}
Sign up to request clarification or add additional context in comments.

Comments

2

You never initialize any of the objects in your array.

arr[0] = new Person();

Comments

1

You have not initialized array of persons. First initialize object of array like this

 Person arr[] = new Person [2];
 arr[0]=new Person ();
 arr[1]=new Person ();

Now set age of person :-

 arr[0].setAge(20);
 arr[1].setAge(25);

Comments

0

new Person[2] creates an array which can hold two person objects at arr[0] and arr[1] (basically equal to null).But you have not initialized arr[0] to a new Person object at each location. So when try to set value for the object locating at arr[0] you are trying to set the age to a null object which throws you a null pointer exception..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.