...
This noncompliant example shows a bug in Tomcat version 4.1.24, initially discovered by Reasoning [Reasoning 2003]. The cardinality()
method was designed to return the number of occurrences of object obj
in collection col
. One valid use of the cardinality()
method is to determine how many objects in the collection are null
. However, because membership in the collection is checked using the expression obj.equals(elt)
, a null pointer dereference is guaranteed whenever obj
is null
and elt
is not null
.
...
This compliant solution uses an Optional String
instead of a String
object that may be null. The Optional
class ([API 2014] java.util.Optional
) was introduced in Java 8 and can be used to mitigate against null pointer dereferences.
...
The Optional
class contains methods that can be used to make programs shorter and more intuitive [Urma 2014].
Exceptions
EXP01-EX0: A method may dereference an object-typed parameter without guarantee that it is a valid object reference provided that the method documents that it (potentially) throws a NullPointerException
, either via the throws
clause of the method or in the method comments. However, this exception should be relied upon sparingly.
...
Null pointer dereferences can happen in path-dependent ways. Limitations of automatic detection tools can require manual inspection of code [Hovemeyer 2007] to detect instances of null pointer dereferences. Annotations for method parameters that must be non-null can reduce the need for manual inspection by assisting automated null pointer dereference detection; use of these annotations is strongly encouraged.
...
Java Web Start applications and applets particular to JDK version 1.6, prior to update 4, were affected by a bug that had some noteworthy security consequences. In some isolated cases, the application or applet's attempt to establish an HTTPS connection with a server generated a NullPointerException
[SDN 2008]. The resulting failure to establish a secure HTTPS connection with the server caused a denial of service. Clients were temporarily forced to use an insecure HTTP channel for data exchange.
...
Android applications are more sensitive to NullPointerException
due to the constraint of the limited mobile device memory. Static members or members of an Activity may become null when memory runs out.
Bibliography
[API 2006] | |
[API 2014] | Class java.util.Optional |
| |
Defect ID 00-0001 | |
| Null Pointer Dereference |
[SDN 2008] | |
[Urma 2014] | Tired of Null Pointer Exceptions? Consider Using Java SE 8's Optional! |
...