NullPointerException in Java — How to Fix (2026) | Tutorials Logic
What is This Error?
The NullPointerException (NPE) is the most common Java runtime exception. It occurs when you try to use a reference variable that points to null — calling a method, accessing a field, or using it in an operation when no object has been assigned.
Error Message:
Exception in thread "main" java.lang.NullPointerExceptionat com.example.Main.main(Main.java:10)
Common Causes
Quick Fix (TL;DR)
// ❌ Problem
String name = null;
System.out.println(name.length()); // NullPointerException!
// ✅ Solution 1: Null check
if (name != null) {
System.out.println(name.length());
}
// ✅ Solution 2: Optional (Java 8+)
Optional.ofNullable(name)
.ifPresent(n -> System.out.println(n.length()));
// ✅ Solution 3: Default value
String result = (name != null) ? name : "default";
Common Scenarios & Solutions
Scenario 1: Uninitialized Object Reference
public class Main {
static String message; // null by default!
public static void main(String[] args) {
System.out.println(message.length()); // NullPointerException!
}
}
public class Main {
static String message = "Hello"; // Initialize with value
public static void main(String[] args) {
System.out.println(message.length()); // 5 — works!
}
}
Scenario 2: Method Returns Null
Map map = new HashMap<>();
String value = map.get("key"); // Returns null if key doesn't exist
System.out.println(value.toUpperCase()); // NullPointerException!
Map map = new HashMap<>();
// Solution 1: getOrDefault
String value = map.getOrDefault("key", "default");
System.out.println(value.toUpperCase()); // "DEFAULT"
// Solution 2: Null check
String value2 = map.get("key");
if (value2 != null) {
System.out.println(value2.toUpperCase());
}
// Solution 3: Optional (Java 8+)
Optional.ofNullable(map.get("key"))
.map(String::toUpperCase)
.ifPresent(System.out::println);
Scenario 3: Chained Method Calls
// Any link in the chain could be null
String city = user.getAddress().getCity().toUpperCase(); // NPE if any is null!
// Solution 1: Null checks at each step
String city = null;
if (user != null && user.getAddress() != null && user.getAddress().getCity() != null) {
city = user.getAddress().getCity().toUpperCase();
}
// Solution 2: Optional chain (Java 8+)
String city = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.map(String::toUpperCase)
.orElse("Unknown");
Scenario 4: Null in Collections
List names = Arrays.asList("Alice", null, "Bob");
for (String name : names) {
System.out.println(name.toUpperCase()); // NPE on null element!
}
List names = Arrays.asList("Alice", null, "Bob");
// Solution 1: Null check in loop
for (String name : names) {
if (name != null) {
System.out.println(name.toUpperCase());
}
}
// Solution 2: Stream with filter
names.stream()
.filter(Objects::nonNull)
.map(String::toUpperCase)
.forEach(System.out::println);
Best Practices to Avoid This Error
Related Errors
Key Takeaways
- NullPointerException occurs when calling methods or accessing fields on a null reference
- Always check for null before using object references from methods or collections
-
Use Optional
in Java 8+ to explicitly handle nullable values - Initialize variables with default values instead of leaving them null
- Return empty collections instead of null from methods
- Use Objects.requireNonNull() to fail fast with clear error messages
Frequently Asked Questions
Level Up Your Core java Skills
Master Core java with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related Java Topics