🔧 Error Fixes
· 2 min read

NullPointerException — How to Fix It (Java, Kotlin, C#)


java.lang.NullPointerException
System.NullReferenceException: Object reference not set to an instance of an object
kotlin.KotlinNullPointerException

You’re calling a method or accessing a property on an object that is null. Something you expected to have a value doesn’t.

Fix 1: Check for Null Before Using

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

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

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

Fix 2: Uninitialized Variable

// ❌ Declared but never assigned
String message;
System.out.println(message.length());  // 💥 NPE

// ✅ Initialize with a default
String message = "";

Fix 3: Method Returns Null

// ❌ Map.get() returns null if key doesn't exist
Map<String, String> config = new HashMap<>();
String value = config.get("missing_key");
value.toUpperCase();  // 💥 NPE

// ✅ Use getOrDefault
String value = config.getOrDefault("missing_key", "default");

Fix 4: Array or List Element Is Null

// ❌ Array has null elements
String[] names = new String[5];  // All null
names[0].length();  // 💥 NPE

// ✅ Check element before use
if (names[0] != null) {
    names[0].length();
}

Fix 5: Chained Method Calls

// ❌ Any link in the chain could be null
String city = user.getAddress().getCity().toUpperCase();  // 💥

// ✅ Use Optional chaining
String city = Optional.ofNullable(user)
    .map(User::getAddress)
    .map(Address::getCity)
    .map(String::toUpperCase)
    .orElse("Unknown");
// C# — null-conditional operator
string city = user?.Address?.City?.ToUpper() ?? "Unknown";
// Kotlin — safe calls
val city = user?.address?.city?.uppercase() ?: "Unknown"

Fix 6: Spring/Framework Injection Failed

// ❌ @Autowired field is null
@Autowired
private UserService userService;  // null if not a Spring bean

// ✅ Make sure the class is a Spring component
@Service  // or @Component, @Controller
public class MyClass {
    @Autowired
    private UserService userService;
}

Debugging

// Add null checks with descriptive messages
Objects.requireNonNull(user, "User cannot be null");
Objects.requireNonNull(user.getAddress(), "User address cannot be null");