NullPointerException problem

exercise No. 257

Q:

Consider the following method inside a class mi.NpeString:

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * <p>Calculate the sum of lengths of all strings belonging to a
 *    given array.</p>
 *
 * <p>Example: The array {"a", "string"} consists of two strings
 *    having lengths 1 and 6 respectively. The
 * overall sum of lenghts is thus 1 + 6 == 7.</p>
 *
 * @param strings An array of string or null values.
 * @return The sum of all string's length values.
 *    <code>null</code> entries will be treated as empty strings.
 */
static int getLength(final String[] strings) {
  int length = 0;
  for (final String s: strings) {
    length += s.length();
  }
  return length;
}

We observe the following NullPointerException (NPE) run-time error at line 26:

Exception in thread "main" java.lang.NullPointerException
  at mi.NpeString.getLength(NpeString.java:26)
  at ...

What caused this NPE error?

  1. Explain the implementation error with respect to the provided Javadoc promise

  2. Provide a possible sample data array of String[] type causing the exception.

  3. Propose a solution resolving the underlying flaw.

A:

  1. The Javadoc contract regarding our method getLength(final String[] strings)'s parameter strings states:

    /**
     ...
     * @param strings An array of string or null values.
     ...

    There is no guard around the s.length() term. Therefore any such null value will cause a NPE.

  2. The strings array may thus contain null values:

    String[] names = {"Jim", null}; 
    int length = getLength(names); // Will cause a NPE
  3. The local variable s may therefore become null causing a NullPointerException when invoking s.length() We thus require an if - guard filtering null values beforehand:

    static int getLength(final String[] strings) {
      int length = 0;
      for (final String s: strings) {    
        if (null != s) {
           length += s.length();
        }
      }
      return length;
    }