NullPointerException problem

Consider the following method inside a class mi.NpeString:

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 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? Provide a possible sample data array causing this exception. Explain the implementation error with respect to the provided Javadoc promise and propose a solution resolving the flaw.

Solution

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

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

The variable strings may thus contain null values e.g.:

String[] names = {"Jim", null, "Eve"}; 
int length = getLength(names); // Will cause a NPE

The local variable s may therefore become null causing a NullPointerException when invoking s.length() requiring 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;
}