null pointer exception (with rectangles)

I have allways assumed that this exception occurs when memory is not allocated for an array before it is used. Now after I added the code that alocated the memory where it was needed, it still threw the exception, so I added lines 7-15 to this:

public void setOutline(int aniID, int x, int y, int w, int h)
    {
        xloc = x;
        yloc = y;
        width[aniID] = w;
        height[aniID] = h;
        try
        {
            outline[aniID].setRect(x,y,w,h);
        }
        catch(NullPointerException exc)
        {
            outline = new Rectangle[width.length];
            outline[aniID].setRect(x,y,w,h);
        }
    }

and lo and behold it is still throwing the same exception (now coming from line 14) after memory was allocated on the previous line. How is this happening, Ty for any help?

new Rectangle[n]; // creates an array filled with NULL elements

ah your right, I had forgotten that…Ty

If I know there is a chance of a null pointer by nature, I just do this to go around:

if (obj != null) 

and take it from there. See if you can avoid doing that though.

Note that my ‘fix’ will allocate a new Rectangle[n] every time a null element is encountered, which is not what you want.


public void setOutline(int aniID, int x, int y, int w, int h)
    {
        xloc = x;
        yloc = y;
        width[aniID] = w;
        height[aniID] = h;

        if(outline == null) 
            outline = new Rectangle[width.length];

        if(outline[aniID] == null) 
            outline[aniID] = new Rectangle();

        outline[aniID].setRect(x,y,w,h);
    }

NullPointerException is just the use of a anything that is null. In the case of the array, nullpointerexception happens because the requested array slot is null-nonexistant. This can be simply debugged using

if(var != null) System.out.println();