Avoiding NullPointerException in Java

I use x != null to avoid NullPointerException. Is there an alternative?

if (x != null) {
    // ...
}

Comments

  1. 4


    Other than catching the error, if you are going to work with something which might be null, you might want to throw in null checks.

    What you could do to reduce the chances of having to make null checks, would be to never return null from your methods, unless it is really necessary, for instance:

    public IList getUserNames()
    {
    //No usernames found...
    return new ArrayList();

    //As opposed to returning null
    return null;
    }
    By returning the empty list, a call to the above code would result into something like so: for(String name : this.getUserNames()) {...}. If no user names where found, the loop will not execute.

    If on the other hand, you return null, you would need to do something like so:

    List userNames = this.getUsernames();
    if(userNames != null)
    for(String userName : userNames) {....}

    ReplyDelete

Post a Comment

Popular posts from this blog

How do I generate random integers within a specific range in Java?

#1 javascript toturial

Proper use cases for Android UserManager.isUserAGoat()?