Reputation: 3462
While running this code
public class Main
{
public int a;
public int b;
public static void main(String []args)
{
Main []ary=new Main[26];
int i;
for(i=0;i<26;i++)
{
ary[i].a=0;
ary[i].b=i;
}
}
}
I am getting the following error..
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:11)
I created an array of objects for the same class and trying to use its instance variables
Though I searched for it, i am not able to find the mistake..
Upvotes: 1
Views: 1626
Reputation: 121998
Main []ary=new Main[26];
You declared array
not assigned values in it.
So in memory, you array looks like Main []ary={null,null ...., null};
Thrown when an application attempts to use null in a case where an object is required. These include:
It's like null.a
which causes NullPointerException
.
for(i=0;i<26;i++)
{
Main m = new Main();
m.a =0;
m.b =i;
ary[i]= m;
}
Upvotes: 4
Reputation: 116
ary[i] is null
public class Main
{
public int a;
public int b;
public static void main( String[] args )
{
Main[] ary = new Main[26];
int i;
for ( i = 0; i < 26; i++ )
{
ary[i]=new Main();//<---(here ary[i] was null)
ary[i].a = 0;
ary[i].b = i;
}
}
}
Upvotes: 1
Reputation: 11911
You just created an array that can hold instances of Main
, but you didn't initialize the contents, so all elements of the array are null
. Do ary[i]= new Main()
before assigning the values.
Upvotes: 0
Reputation: 13713
You need to create an instance for each of the array's entries in order to access it :
for(i=0;i<26;i++)
{
ary[i] = new Main(); // Otherwise ary[i] is null and will cause an exception on the following line
ary[i].a=0;
ary[i].b=i;
}
Upvotes: 1
Reputation: 3544
Main []ary=new Main[26];
int i;
for(i=0;i<26;i++)
{
ary[i]=new Main();
ary[i].a=0;
ary[i].b=i;
}
This will work :)
Upvotes: 2