user2441441
user2441441

Reputation: 1387

Java null pointer exception while calling method in another class

I have something similar to:

       public class A{
    public static B[] bObj;

    public A(){
        bObj = new B[2]; // create array of objects of class B
    }

    public static void main(String[] args){
        A aObj = new A();
        for(i=0;i<2;i++){
            bObj[i].testprint();
        }

    }
}

class B{
    public testprint(){
        System.out.println("Inside testprint()");
    }
}

When I run this, I get NullPointer exception at bObj[i].testprint(). I did do new B() in the constructor of A. But I don't know why it isn't working.

Upvotes: 0

Views: 890

Answers (1)

Rohit Jain
Rohit Jain

Reputation: 213261

Understand that initializing an array of reference, doesn't really initializes the references inside it. They are still null. You need to initialize them by iterating over the array.

public A(){
    bObj = new B[2];
    for (int i = 0; i < bObj.length; ++i) { bObj[i] = new B(); }
}

Upvotes: 5

Related Questions