dcsimg
November 27, 2020
Hot Topics:

User Code: Avoiding Those Pesky NullPointerExceptions

  • By Russell Thackston
  • Send Email »
  • More Articles »

NullPointerExceptions are a fact of life in Java. Especially since everything is an object, and any object can be null.

Because of this, I have developed a habit of invoking methods only on objects I know have been instantiated.

For example...

  private String _name = "";  // instantiated with a
value and never allowed to be set to null
  public boolean checkName(String newName) {
    return _name.equals(newName);
  }

is much better than...

  public boolean checkName(String newName) {
    return newName.equals(_name);  // this will throw
a NullPointerException if newName is null!!!
  }

... after all, newName might be null and attempting to invoke the .equals() method would throw an exception. However, if _name could also be set to null, then you should use something like...

  public boolean checkName(String newName) {
    if (_name != null) {
      return _name.equals(newName);
    }
    else if (newName != null) {  // _name is null and
newName is not
      return false;
    }
    else {  // both null
      return true;  // or false, depending on your
needs
    }
  }

Not the most elegant code, but effective.

Now, here's the cool part. Did you know you can reverse "hard-coded" comparisons?

  boolean result = "Hello world".equals(testString);  
      // compare a String object to "String"
  boolean result = new Integer(1).equals(testInteger);
 // compare an Integer object to the number "1"

It may look strange having "Hello world" on the left side of the comparison, but it sure beats...

  boolean result = false;
  if (testString != null) {
    result = testString.equals("Hello world");
  }

or even worse, a try/catch that returns false when an exception is thrown.

This approach can be used on any method that accepts a null object as a parameter, such as compareTo(), compareToIgnoreCase(), etc.

About the author

Russell Thackston is a Senior Programmer for the Research and Development Division of Lectra Systems, Inc., in Atlanta, Georgia.

[To contribute a code article to Gamelan, please contact kmurphy@internet.com.]






This article was originally published on May 24, 2001

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Thanks for your registration, follow us on our social networks to keep up-to-date