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 |
|
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;
}