Srinath Mandava
Srinath Mandava

Reputation: 3462

Getting Exception in thread "main" java.lang.NullPointerException

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

Answers (5)

Suresh Atta
Suresh Atta

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};

NullPointerException

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

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

user2826254
user2826254

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

piet.t
piet.t

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

giorashc
giorashc

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

Sachin
Sachin

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

Related Questions