Andrew De Forest
Andrew De Forest

Reputation: 7338

Handling null objects in an array

I have an array with 18 objects in it, and the array is allocated to have 25 objects in it (the remaining 7 objects are null for future use). I’m writing a program that prints out all the non-null objects, but I’m running in to a NullPointerException and I can’t figure out how to get around it.

When I try this, the program crashes with Exception in thread "main" java.lang.NullPointerException:

        for(int x = 0; x < inArray.length; x++)
        {
            if(inArray[x].getFirstName() != null)//Here we make sure a specific value is not null
            {
                writer.write(inArray[x].toString());
                writer.newLine();
            }
        }

And when I try this, the program runs, but still prints the nulls:

        for(int x = 0; x < inArray.length; x++)
        {
            if(inArray[x] != null)//Here we make sure the whole object is not null
            {
                writer.write(inArray[x].toString());
                writer.newLine();
            }
        }

Can anyone point me in the right direction for handling null objects in an array? All help is appreciated!

Upvotes: 1

Views: 184

Answers (1)

Habib
Habib

Reputation: 223277

your check should be:

if(inArray[x] != null && inArray[x].getFirstName() != null)

Upvotes: 9

Related Questions