2

I have a array that can sometimes be null (strings[0]) and I want to be able to detect when its null so I don't get a error and I can tell the user.

I tried a if statement

(if (strings == null){
   //do my code
})

that didn't work. I tried to do try, catch (NullPointerException) but I'm getting an error in my IDE. Any help would be much appreciated.

1
  • Check out my answer. It will show you each index that is null. Commented Feb 22, 2014 at 6:28

4 Answers 4

3
if (strings == null)

returns true if strings is null

what you want is:

if (strings != null)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your advice but strings == null is what I want, it just wasn't working.
2

You should check:

if(array != null && array.length !=0){
    //relevant code
}else{
    //relevant code
}

This helps if the array is not null and is not empty.

5 Comments

I was going to say that! :)
Shouldn't it be array.length instead of array.size()?
Thanks, I tried this and it didn't work but it seems like it should. At this point I am starting to think that the error is coming from somewhere else. Ah code, always seeming like it should work even though it doesn't.
Sorry yes. It should be array.length. Thanks for the edit. Couldn't format properly since I'm on mobile :-)
@NatServ: What is the error? You can edit your answer and paste the whole code so that we can help you figure it out.
0

Try looping through your strings array and checking for the null objects like so:

for (int i = 0; i < strings.length; i++) {
    if (strings[i] == null) {
        System.out.println("The item at index [" + i + "] is null!");
    }
}

Comments

0

Going off of what others have stated earlier

if (strings == null)
    //code here

This pattern works great. A point to remember if you want to combine conditionals using the short circuit &&, || operators.

These two logical operators stop when the boolean value can be determined.

so if we have

if (strings == null && someFunction() == anotherFunction())

in the case that strings is null

someFunction() == anotherFunction() //<- this would not be evaluated.

because false && anyotherBool will never be true

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.