1

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();
0

3 Answers 3

5

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();
}
Sign up to request clarification or add additional context in comments.

Comments

3

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"

Comments

0

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.

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.