0

When I run my method to print out the array, it will give me a NullPointerException and I have no idea how to get it to just print what I want. Let's say I want Array[0] to be "Sally" and Array[3] to be "Jeff", I want it to print out 0, Sally 3, Jeff. While leaving all the null slots of the array alone.

Here's my code:

public void printAll()
{       
    for(int i = 0; i <= 10; i++)
    {
        if(seats[i].equals(null))
        {
            System.out.print(i + " , " + seats[i] + "\n");              
        }

    }
}

Any help would be greatly appreciated, if I'm being too vague I can reply with more details.

1
  • 1
    null has no equals, use == Commented Feb 19, 2014 at 6:34

6 Answers 6

1

You need:

if (seats[i] != null)

Using equals will cause a de-reference, which is exactly what you're trying to avoid.

Sign up to request clarification or add additional context in comments.

Comments

1

You should not use:

if(seats[i].equals(null))

That condition will itself throw a NPE. You should use:

if(seats[i] != null)

Comments

0

Change if(seats[i].equals(null)) to if(seats[i] != null) or if(seats[i] == null) to avoid NPE.

Because, if seats[i] is null you cannot call methods on null references.

Comments

0

You may want to use the following: (you were checking equality of objects, not whether the array item was null.

public void printAll()
{   
...
    if (seats != null) {
        for (int i=0; i < seats.size(); i++) {
            if (seats[i] != null) {
                System.out.println(i + ", " + seats[i]);  
            }
        }
    }  

}

Comments

0
if(seats[i].equals(null)) {
  System.out.print(i + " , " + seats[i] + "\n");              
}

This is causing your null pointer exception because seats[i] is equal to null. When you have a null object, you can't reference it. At all. This is logical because if you have nothing, then you can't ask what it has.

To fix this, the best way to check if something is equal to null is by going if(Object == null) and if it ISN'T null then, if(Object != null). These are very common through any code you may have.

Jarod.

Comments

0

public static void printAll(){

  String[] seats={"Jerry","chen","Jack"};
  for(int i = 0; i <seats.length; i++)
  {

if(!seats[i].equals(null))
    {
        System.out.print(i + " , " + seats[i] + "\n");              
    }  

}

Comments

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.