0

When working on a program for school, I created a method which returned the index of an array based on the value you gave the method. The method throws a NullPointerException but in every index of the array has already been instantiated. To show this, I created a test program which does the same thing.

public class Test {
private static Number[] numbers = new Number[16];

public static void main(String[] args) {
    new Test();
}

public Test() {
    for (Number n : numbers) {
        n = new Number(0);
    }
    System.out.println(get(0).value);
}

public Number get(int index) {
    return numbers[index];
}

class Number {
    public int value;

    public Number(int value) {
        this.value = value;
        }
    }
}

When run this should print the value of the Integer "value", in this case of the object in the first position of the array.

I am sure there is a simple explanation to this, but I am unaware of the problem.

1 Answer 1

4

You have to use the for-each loop for read-only passes. Currently, in your constructor, the elements in your array still remain uninitialized and hence the error.

So change it to a normal for loop.

for(int i = 0; i < numbers.length; i++){
    numbers[i] = new Number(0);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you immensely! I had no idea the for each loop did not act exactly like the regular for loop.
@piechesse Yes, you can read the link I provided, particulary at the end ;)

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.