1

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..

5 Answers 5

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

    }
Sign up to request clarification or add additional context in comments.

Comments

2
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 :)

Comments

1

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.