Why NullPointerExceptions Still Haunt Java Developers—and How to Defeat Them
Java developers constantly battle NullPointerExceptions, a historic flaw introduced by Tony Hoare, but modern JDKs provide clearer messages and defensive techniques—such as explicit null checks, utility methods, avoiding null returns, and using Optional—can dramatically reduce these runtime errors.
Origin of Null Pointers
Null references were introduced by Tony Hoare in 1965 when designing ALGOL 60, and later adopted by many languages such as C, C++, C#, Go, while languages like Rust avoid them. Hoare later called the null reference “the billion‑dollar mistake”.
Since JDK 14, NPE messages include more context, e.g.:
Cannot invoke "String.length()" because "s" is nullHow to Deal with Null Pointers
Defensive programming helps prevent NullPointerExceptions.
1. Proactively check for null. Example:
public static boolean isEmpty(CharSequence cs) {
return cs == null || cs.length() == 0;
}Many utility libraries provide isEmpty, isNotEmpty, isNotBlank, or CollectionUtil.isEmpty methods.
2. Avoid returning null. Return an empty collection or optional instead of null.
3. Throw an exception when appropriate. Providing a clear exception is better than returning null.
Traditional nested null checks can become verbose:
public static String getUserOrderDetail(Integer userId) {
User user = User.getUser(userId);
if (user != null) {
Order order = user.getOrder();
if (order != null) {
Address address = order.getAddress();
if (address != null) {
String detail = address.getDetail();
if (detail != null) {
return detail;
}
}
}
}
return "Sorry, not found";
}Java 8’s Optional simplifies the flow:
public static String getUserOrderDetail(Integer userId) {
return Optional.ofNullable(User.getUser(userId))
.map(User::getOrder)
.map(Order::getAddress)
.map(Address::getDetail)
.orElse("Sorry, not found");
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
