Quick Answer
Prevent NPEs in Java applications.
Understanding the Issue
Occurs when trying to access methods/properties of null objects. Java 14+ provides more helpful error messages. Always validate objects before use.
The Problem
This code demonstrates the issue:
Java
Error
String str = null;
int length = str.length(); // Throws NPE
The Solution
Here's the corrected code:
Java
Fixed
// Solution 1: Defensive checks
if (str != null) {
length = str.length();
}
// Solution 2: Optional (Java 8+)
Optional<String> opt = Optional.ofNullable(str);
length = opt.map(String::length).orElse(0);
// Solution 3: Objects.requireNonNull
String safeStr = Objects.requireNonNull(str, "str cannot be null");
Key Takeaways
Use proper null-checking and Optional for safety.