1

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!

10
  • 2
    I am surprised that the second version doesn't work. Are you sure it still prints the nulls? Commented May 8, 2012 at 17:47
  • 1
    I think Louis is correct. There is not any problem with the second version of code. Commented May 8, 2012 at 17:48
  • "but still prints the nulls", are you sure? Have you overrided the method toString() in your class? Commented May 8, 2012 at 17:49
  • 1
    the object is not null, but its firstname is (may be) Commented May 8, 2012 at 17:49
  • @LouisWasserman Maybe: inArray[x] != null but inArray[x].toString() prints null. Commented May 8, 2012 at 17:50

1 Answer 1

9

your check should be:

if(inArray[x] != null && inArray[x].getFirstName() != null)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Habib.OSU, I will accept this when I can. So simple, not sure why I didn't try it!

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.