Quick Answer
Avoid and handle null references.
Understanding the Issue
This runtime exception occurs when trying to dereference a null object, indicating missing object initialization.
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: Use Optional (Java 8+)
Optional<String> opt = Optional.ofNullable(str);
length = opt.map(String::length).orElse(0);
// Solution 3: Validate parameters
public void process(String input) {
Objects.requireNonNull(input, "Input cannot be null");
// ...
}
// Solution 4: Annotations (@Nullable, @NonNull)
public void process(@NonNull String input) {
// ...
}
Key Takeaways
Validate object references before use and leverage Optional for nullable values.