P R
P R

Reputation: 1301

why the Nullpointerexception?

This is the scenario:

class A{
int a;
}

class B{
A objectA[]=new A[10] ;
}

class C{
B ObjectB;
public static void main(String[] args){
ObjectB.ObjectA[0].a=1;
}
}

I get a nullpointerexception in main operation. However if I declare just one object of class A, I don't get the error. Why so? How do I rectify it?

Upvotes: 0

Views: 103

Answers (3)

Shail
Shail

Reputation: 21

You have not initialized the ObjectB. There is no memory allocated to ObjectB. Hence showing null pointer exception (Nothing is allocated to ObjectB reference).

This should work:

class C { B ObjectB = new B();

public static void main(String[] args) {
    ObjectB.ObjectA[0].a = 1;
}

}

Upvotes: 0

sverre
sverre

Reputation: 6919

calling new B() initializes an array of objects of type A, but none of the member objects. You can rectify it first initializing objectB and then calling objectA[i] = new A() for each item in the array.

class B{
    A objectA[]=new A[10] ;
    {
        for (int i = 0; i < 10; i++)
            objectA[i] = new A();
    }
}

class C{
B ObjectB = new B();
public static void main(String[] args){
ObjectB.ObjectA[0].a=1;
}
}

Upvotes: 1

amit
amit

Reputation: 178521

(1) B ObjectB; does not create a new instance of B, it just crate the variable, to crate an instance; B ObjectB = new B();

(2) Also A objectA[]=new A[10] ; allocates the array, but not elements in the array, and ObjectB.ObjectA[0].a=1; will also cause NPE.

Upvotes: 5

Related Questions