Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have this piece of code which is throwing a Null Pointer exception at the commented line.. I think that it may be because I haven't initialized the array ParentInterfaces am I right??...the problem is since this array may contain a number of elements ranging from 2 to 30 I would not like the idea of initializing it in constructor second if I do that woudn't it result in a memory leak in function2 as I have an object there whose reference I am passing to another function????...Is there any other alternative available???

public class Class {
    public String modifier;
    public String name;
    public  Class parent;
    public  Interface[] parentInterfaces;
    public Method[] memberFunctions;
    public Class[] nestedClasses;
    public Interface[] nestedInterfaces;
    public Field[] memberData;
    public int methodCount, classCount, interfaceCount, fieldCount, parentInterfaceCount;

public Class (String classModifier,String className)
{
    modifier=classModifier;
    name=className;
    methodCount=0;
    classCount=0;
    interfaceCount=0;
    fieldCount=0;
    parentInterfaceCount=0;     
}

public void setParentInterfaces (Interface[] interfaces)
{
    while (interfaces[parentInterfaceCount] != null)
    {
// This is the line which throws the NPE
        parentInterfaces [parentInterfaceCount] = interfaces [parentInterfaceCount]; 

parentINterfaceCount++; } } Now the piece of code which results in a call to this function is: (It belongs to a diff function in a diff class)

    // Prev Code    
    else if (child.getNodeName()=="ParentInterface")
    {
        Iflag=1;
        //Element ele=(Element)child;
        JOptionPane.showMessageDialog (null, "Parent Interface found" + child.getTextContent () + "for " + classes[i].name);
        parentInterfaces[parentICount] = new dataObjects.Interface (child.getTextContent ());
        // classes[i].parentInterfaces[parentICount] = new dataObjects.Interface (child.getTextContent ());
        parentICount++;
    }
}
classes[i].setParentInterfaces (parentInterfaces);
share|improve this question
1  
can't you just do this in setParentInterfaces: parentInterfaces = new Interface[interfaces.Length], before the while loop –  forsvarir May 4 '11 at 22:03
 
where is classes[i] getting set? –  CoolBeans May 4 '11 at 22:05
 
@CoolBeans: it gets set properly. in earlier portions of the codes..I have verified it.as I can access other properties like classes[i].name properly... –  Sudh May 4 '11 at 22:08
 
@forsvarir: wow..thats a cool option to use..but I think its better I d change all the arrays to arraylist... –  Sudh May 4 '11 at 22:11
add comment

6 Answers

up vote 1 down vote accepted

You declare the parentInterfaces variable but don't initialize it. Try this ....

public void setParentInterfaces(Interface[] interfaces)
{
    parentInterfaces = new Interface[interfaces.length]
    while(interfaces[parentInterfaceCount]!=null)
    {
        parentInterfaces[parentInterfaceCount]=interfaces[parentInterfaceCount]

    }

}
share|improve this answer
1  
But the while() loop is broken - parentInterfaceCount isn't being incremented, so the loop will execute either never, or for ever! –  DNA May 4 '11 at 22:14
 
@DNA - you're not wrong about that .... but I took the original question to be "Why Am I getting a NullPointerException"? I didn't look any further than that. –  DaveHowes May 4 '11 at 22:20
 
yes DNA is right...I edited the question....thnx for the chk –  Sudh May 4 '11 at 22:23
add comment

Yes, this is because you haven't initialised parentInterfaces.

Your options include:

  1. initialising the array with the maximum size expected (30).
  2. using a resizable Collection (such as ArrayList), which will require some restructuring of your current code, I think.
  3. Using System.arraycopy to copy the interfaces array into the parentInterfaces array

Incidentally, your setParentInterfaces() method won't work, as the array index isn't being incremented.

share|improve this answer
 
yes I agree....will give 2nd or 3rd a try...depends on how much restructuring work is required –  Sudh May 4 '11 at 22:28
add comment

Consider using an ArrayList<Interface> instead of an array, then add items with parentInterfaces.add(item) and retrieve them with parentInterfaces.get(). ArrayLists take care of memory allocation for you.

In fact, it might be better to use ArrayLists instead of arrays for all of your variables.

share|improve this answer
 
Will look into that.... –  Sudh May 4 '11 at 22:10
add comment

You should generally initialize arrays before using them. Also, don't name your class Class. That already exists in the java.lang package.

share|improve this answer
 
thanx for the check..ll try to change it.. –  Sudh May 4 '11 at 22:12
add comment

You have not initialized your array. You need to do something like this

parentInterfaces = new Interface[];

Although I must say its a funny code. You do not need to maintain arraycounts in variables in java. you can just say arrayObject.length();

I say pick up a good java book :)

share|improve this answer
 
well I dont know how it looks funny but arrayObject.length will give you size of the array, i.e you get 50 if you do new Interface[50], irrespective of the number of actual objects present in array..not favorable in my case....second the solution you provide won't even compile...n give an error: Variable must provide either dimension expressions or an array initializer...... So may be you would like to read that java book once again...:) –  Sudh May 4 '11 at 22:19
add comment

the problem is since this array may contain a number of elements ranging from 2 to 30 I would not like the idea of initializing it in constructor second if I do that woudn't it result in a memory leak in function2 as I have an object there whose reference I am passing to another function????

Simple answer: No. Initializing an array does not create any objects, just an array of null pointers. Even if it did, Java makes worrying about memory "leaks" a bad idea. On theother hand, it can be worth it to worry about memory usage. Since it is a garbage collected language the thing to ask is: can the garbage collector keep my memory footprint small? The primary rule to garbage collector utilization is: dont keep extra pointers to stuff around on the heap. Having pointers set to null on the heap is almost always okay from a memory standpoint. Pointers on the stack are also almost always okay.

On your code:

Your code is hard to read because 1. It is totally not clear what is supposed to do (is this part of a compiler?) 2. Your naming scheme uses keywords in the language/names of the classes used in reflection 3. You have a fair bit of code here, generally it is best to fork tour code and start simplifying it until the absolutely most minimal code that produces your error.

In particular, I dont know what this piece of code is supposed to do:

    while(interfaces[parentInterfaceCount]!=null)
    {
        parentInterfaces[parentInterfaceCount]=interfaces[parentInterfaceCount];

    }

Because you dont increment parentInterfaceCount, this code will either do nothing, or will enter an infinite loop. So, it is very hard for me to figure out what you want. The reason you are getting a null pointer exception is that parentInterfaces[parentInterfaceCount] could only be addressed if parentInterfaces is initialized.

It would be easier to help if I knew what you wanted to accomplish.

That said I think you have two options: either initialize the array to the maximum size expected or use the length of the array being passed to you to compute a size to initialize to at runtime.

Some ideas to make life simpler:

  1. Use a built in array copy method like System.arraycopy
  2. Use a for loop--it makes handling things like incrementing a pointer much easier
  3. Use a collection class
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.