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.
// ❌ 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";
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!
}
}
Map<String, String> map = new HashMap<>();
String value = map.get("key"); // Returns null if key doesn't exist
System.out.println(value.toUpperCase()); // NullPointerException!
Map<String, String> 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);
// 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");
List<String> names = Arrays.asList("Alice", null, "Bob");
for (String name : names) {
System.out.println(name.toUpperCase()); // NPE on null element!
}
List<String> 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);
NPE occurs when you try to use a null reference "” calling a method, accessing a field, or using it in an operation. The reference variable exists but doesn't point to any object.
Read the stack trace "” it shows the exact class, method, and line number. In Java 14+, helpful NPE messages tell you exactly which variable was null.
Optional<T> is a container that may or may not contain a value. It forces you to explicitly handle the null case using methods like orElse(), ifPresent(), and map(), making null handling visible in the code.
Always return empty collections (Collections.emptyList(), new ArrayList<>()) instead of null. This prevents NPE in callers and follows the Null Object pattern.
Use Optional for nullable returns, initialize variables, use @NonNull annotations, return empty collections instead of null, use Objects.requireNonNull() for validation, and enable static analysis tools.
Explore 500+ free tutorials across 20+ languages and frameworks.