Bugs
Java NullPointerException: Causes and Prevention
NullPointerException is Java's most common runtime error. It occurs when you call a method or access a field on a null reference.
❌ Code Prone to NPE
public String getUserCity(long userId) {
User user = userRepository.findById(userId); // Returns null if not found
return user.getAddress().getCity(); // NPE if user or address is null
}✅ Fixed with Optional
import java.util.Optional;
public Optional<String> getUserCity(long userId) {
return userRepository.findById(userId)
.map(User::getAddress)
.map(Address::getCity);
}
// Caller:
String city = getUserCity(42).orElse('City unknown');💡
Pro tip: Annotate with @NonNull and @Nullable. IDEs like IntelliJ perform null-flow analysis and warn about potential NPEs before you run the code.
Paste this code into LearnCodeGuide
Detect Java vulnerabilities and bugs automatically with AI-powered analysis.
Analyze Java Code →