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");