Avoiding null pointer exception

20 July 2008

One should try avoiding null pointer exception. In case of coding an application that needs high degree of reliability, don’t take risks. I will present an example.

Check the following piece of code.

private boolean isNullString(String string) {
return (string.equals(""));
}

It seems a normal piece of code. But still there’s a hidden trap here. What is the string which is passed is null? So try to rephrase the code as given below.

private boolean isNullString(String string) {
return ("".equals(string));
}

This should work now without any null pointer exceptions.

del.icio.us:Avoiding null pointer exception  digg:Avoiding null pointer exception  spurl:Avoiding null pointer exception  wists:Avoiding null pointer exception  simpy:Avoiding null pointer exception  newsvine:Avoiding null pointer exception  blinklist:Avoiding null pointer exception  furl:Avoiding null pointer exception  reddit:Avoiding null pointer exception  fark:Avoiding null pointer exception  blogmarks:Avoiding null pointer exception  Y!:Avoiding null pointer exception  smarking:Avoiding null pointer exception  magnolia:Avoiding null pointer exception  segnalo:Avoiding null pointer exception  gifttagging:Avoiding null pointer exception

Top Of Page | Trackback

If you found this page useful, consider linking to it. Simply copy and paste the code below into your web site.

It will look like this: Avoiding null pointer exception

3 Responses to “Avoiding null pointer exception”

  1. Yogesh Says:

    what if passed string is “” (which is not null), but the method will return true.
    The correct would be
    return string == null;

  2. peter lawrey Says:

    A feature of IntelliJ is that it tracks which values can and cannot be null. It has annotations to support this but works out a lot for you.
    It also has a quick fix for this use case. If you have object.equals(”string literal”) it can replace with “string literal”).equals(object) you can do the replace on your entire code base in one go if you wish. :)
    However for string.equals(”") it has another suggestion.
    (string != null && string.length() == 0)
    or just string.length() == 0 if it is known the string cannot be null.

  3. Shubhashish Says:

    Another way could be like i have method that accepts the String as a parameter like
    public void setCarName(String carname);

    so i could implemented it like
    public void setCarName(String carname)
    {
    if( carname != null && !(carname.equals(”")) )
    {
    this.carname = carname;
    }
    }

    this way to we can avoid the Null Pointers .

    Another possible way could be using a good IDE., as peter said.

Leave a Reply