1

When I run this code,

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


class Posting
{
    String title;
}

public class Test
{
    Posting[] dew()
    {
        Posting[] p = new Posting[100];
        for(int i = 0; i <p.length; i++)
        {
            p[i].title  = "this is " + i;
        }
        return p;
    }

    public static void main(String args[])
    {
        Test t = new Test();
        Posting[] out = t.dew();

        for(int i = 0; i < out.length; i ++)
        {
            System.out.println(out[i].title);
        }
    }
}

I get this error, run:

Exception in thread "main" java.lang.NullPointerException
    at mistAcademic.javaProject.newsBot.core.Test.dew(Test.java:20)
    at mistAcademic.javaProject.newsBot.core.Test.main(Test.java:29)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Could you have any idea?

1
  • Array is empty.. Posting object is not created how can you access its title field Commented Jan 6, 2013 at 9:18

5 Answers 5

11

You have to initialize the array element before setting fields on it.

p[i] = new Posting(/* ... */);
// THEN set the fields
p[i].title = /* ... */;
Sign up to request clarification or add additional context in comments.

Comments

9
Posting[] p = new Posting[100];

This will only create the array itself, all entries are set to null.

So you need to create the instances and put them into the array as well.

    for( int i = 0; i <p.length ; i++ )
    {
        p[i] = new Posting();    // <=  create instances
        p[i].title  = "this is " + i ;
    }

Comments

4

you have to init your postings

Posting[] dew()
    {
        Posting[] p = new Posting[100];

        for( int i = 0; i <p.length ; i++ )
        {
            p[i] = new Posting();
            p[i].title  = "this is " + i ;
        }

        return p ;
    }

Comments

1

You need to initialize each object of the array. Add following lines before

p[i] = new Posting();
p[i].title  = "this is " + i ; in the for loop.

Comments

0

By doing : Posting[] p = new Posting[100];

will create an array of 100 null objects. p[0], p[1], p[2]..... p[99] = null so when you do :

 p[i].title 

its actually same as : null.title and hence you get NullPOinterException.

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.