Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm kind of new to Java and I've had trouble working with object arrays, the answer is probably pretty simple but I can't see it.

I have a class named Vectors and a function named set_components() What I try to do is create an array of objects like this:

Vectors[] vec = new Vectors[2];

//Then access the function like this:

vec[0].set_components();

However I get this error: Exception in thread "main" java.lang.NullPointerException why is that?

It works if I just do this for one object.

Vector vec = new Vector();
vec.set_components();
share|improve this question
add comment

3 Answers

up vote 4 down vote accepted

Your array has been constructed but is filled with nothing, with null references. If you try to use an item in the array before you've filled the array with instances, you'll get a NPE as you're seeing. Think of an object array like an egg crate. You must first fill it with eggs (Vector objects) before you can use them to make an omelette. Often this is done with a for loop.

for (int i = 0; i < vectors.length; i++) {
  vectors[i] = new Vector();
}
share|improve this answer
 
Thanks! It works now :) Loved your explanation. –  Mario Fuentes Feb 19 '13 at 3:46
 
@MarioFuentes: glad it helped! –  Hovercraft Full Of Eels Feb 19 '13 at 3:48
add comment

Each of those Vectors should be initialized

like this:

for(int i = 0; i < vec.length; i++){
    vec[i] = new Vector();
}

Vectors[] vec = new Vectors[2] line creates 2 "Vectors" references, not "Vectors" objects.

Each of those refer to null initially. Then, when you try to reference null reference of say, vec[0] with vec[0].set_components();, the JVM says "hold on, vec[0] is pointing to null. I can't dereference it.. let me just throw an exception called NullPointerException"

share|improve this answer
add comment

Java objects never appear as expressions, variables, arguments, or array elements. If it is not a primitive it is a reference. A reference is either null, or a pointer to an object.

You created an array of null references. You need to change each element of your array to make it a pointer to a Vectors object: vec[0] = new Vectors(); or similar.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.