🔧 Error Fixes
· 1 min read

Java NullPointerException — How to Fix It


java.lang.NullPointerException

You’re calling a method or accessing a field on a null reference.

Fix 1: Check for null

// ❌ user might be null
String name = user.getName();

// ✅ Check first
if (user != null) {
    String name = user.getName();
}

// ✅ Or use Optional (Java 8+)
Optional.ofNullable(user)
    .map(User::getName)
    .orElse("Unknown");

Fix 2: Initialize your variables

// ❌ Not initialized
String name;
System.out.println(name.length());  // NPE!

// ✅ Initialize
String name = "";

Fix 3: Check return values

// ❌ map.get() returns null if key missing
String value = map.get("key");
value.toUpperCase();  // NPE if key doesn't exist!

// ✅ Use getOrDefault
String value = map.getOrDefault("key", "default");