NullPointerException (NPE) is a Java runtime exception thrown when code accesses a null reference (e.g., calling a method on null).
Core Concept
-
Trigger: Attempting to use a null object reference (e.g.,
null.length()). - Type: Unchecked exception; occurs at runtime, not compile time.
- Example:
String name = null;
System.out.println(name.length()); // Throws NPE
- Stack Trace: Points to the line; trace upward for root cause.
Common Causes
- Uninitialized References: Variables default to null if not set.
User user = getUser(id); // Returns null if not found
user.getName(); // NPE
- Null Parameters: Methods receive unexpected null inputs.
- Collection Access: Null lists/maps or missing keys.
Map<String, Integer> map = new HashMap<>();
map.get("key").toString(); // NPE if key absent
- Method Chains: One null in chain fails all.
user.getProfile().getAddress().getCity(); // Fails if profile null
- Concurrency: Race conditions set references to null mid-use.
- External Data: JSON/DB results with null fields.
How to Fix
-
Add Null Checks:
- Use
if (obj != null)before access. - Or
Objects.requireNonNull(obj, "Message");for early failure.
- Use
- Use Optional (Java 8+):
Optional.ofNullable(user)
.map(User::getName)
.orElse("Default");
-
Safe Collection Methods:
- Maps:
map.getOrDefault(key, default). - Lists: Return
Collections.emptyList()if null.
- Maps:
-
Annotations:
-
@NotNull(Lombok/JSR-305) for IDE warnings.
-
-
Debug Steps:
- Read stack trace bottom-up.
- Add logs:
log.debug("Obj: {}", obj);. - Test with null injections.
Prevention Strategies
- Fail Fast: Validate in constructors; throw on null.
-
Immutable Design: Use
finalfields; libraries like Immutables. - Null Objects: Return empty/default objects, not null.
- Tools: Static analysis (SonarQube, IntelliJ inspections).
-
API Docs: Use
@Nullablein Javadocs. - Code Reviews: Checklist for null handling.
Strategy Comparison:
- Null Checks: Pros - Simple; Cons - Verbose; Best for - Legacy code.
- Optional: Pros - Safe chaining; Cons - Overhead; Best for - New code.
- Annotations: Pros - Proactive; Cons - Tool-dependent; Best for - Teams.
- Null Objects: Pros - Clean APIs; Cons - Design effort; Best for - Models.
Key Takeaway
Spot nulls early, check explicitly, use Optional for fluency. Reduces NPEs by 80%+ in practice.
Top comments (0)