Originally posted by Ajay Divakaran:
There are no compilation errors, but when i run the program I get an NullPointerException in the indicated line below. How do I rectify this?
class A
{
int i,j;
}
public class ArrayObjects
{
public static void main( String args[] )
{
A ob[]= new A[5];
for( int i=0; i<5; i++ )
{
ob[i].i=1; //NullPointerException
ob[i].j=2;
}
}
}
Not an SJCD problem but I'll answer befroe it is moved. A ob[]= new A[5]; creates and array of size 5. But the objects within the array have not been intialised so the references default to null. This is the same as the statement A ob[]= {null,null,null,null,null};