3
public class A{

    int val;    
    public A(int val){
        this.val = val;
    }

    public void print() {
        System.out.println(val);

    }


    public static void main(String args[]){

        A[] aList = new A[10];
        int temp =1;

        for(A a : aList){
            a = new A(temp++);          
        }

        for(A a : aList){
            a.print();;         
        }

    }


}

Getting Exception in thread "main" java.lang.NullPointerException at A.main(A.java:28) aList address space Class A objects are stored but again iterate unable to get stored objects, where are the objects stored ?

2 Answers 2

14

a is a local variable of the for loop, so assigning to it doesn't affect the elements of the aList array.

You should use a regular for loop to initialize the array :

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

Comments

3

That's not how an enhanced for works. Use a standard for loop instead:

for(int i = 0; i < aList.length; i++){
   aList[i] = new A(temp++);          
}

The enhanced for uses an Iterator to loop through every element of the array. And since your array only contains null values, you're getting a NullPointerException.

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.