Napmi
Napmi

Reputation: 541

Java: nullPointerException creating Object

So lets say i have this class call A which has a constructor of

       A(String someA, int someB , String[] someC)

and in another class i created a main which has this as a class variable

    private static String[] someC = new String[4];
    private static ArrayList<A> thisA;

then i extract some information from a dat file

                someA= readFile.nextLine(); //some normal string such as  bob Billy
                someB= readFile.nextInt();   //some integer like 5
                unitCode[0] = readFile.next(); //some code such as HITHERE34
                unitCode[1] = readFile.next(); // all the 4 is the same style
                unitCode[2] = readFile.next();
                unitCode[3] = readFile.next();
         thisA.add(new A(someA,someB,unitCode); // create object and store into array list

I tried running this and it gave me a nullPointerException error when i print the unitCode it returns me an address instead . how do i fix this ?

Upvotes: 0

Views: 112

Answers (3)

Sharique
Sharique

Reputation: 859

As you have written "private static ArrayList thisA;" , It means that only the reference variable is created and stored in stack memory but no object is been created in the heap memory and so thisA is currently pointing to no object and has a default value null, and here you are trying to access the object using this variable which is not even created and hence you are getting the nullPointerException.

So make it as, private static ArrayList thisA = new ArrayList; and your problem will be solved

Thanks :)

Upvotes: 0

Mateusz Dymczyk
Mateusz Dymczyk

Reputation: 15141

private static ArrayList<A> thisA;

This is only a declaration of a member. By default the JVM will initialise "thisA" (or any reference type member) to a null value. To overcome this you need to manually initialise it to something else:

private static ArrayList<A> thisA = new ArrayList<A>();

Upvotes: 2

MrSnrub
MrSnrub

Reputation: 1183

You have to initialize the list thisA before being able to execute methods like .add. As long as there is no initialized object, you cannot run methods of the collection.

thisA = new ArrayList<A>();

If you can estimate, how many entries you will need (round about), you might be interested in this constructor:

thisA = new ArrayList<A>(120);

After having initialized the list, you can add elements.

Upvotes: 2

Related Questions