📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
What is NullPointerException?
Why does it occur?
NullPointerException Class Diagram
Java NullPointerException Example
In the below example, the person object is null and we are invoking its fields on null object leads to NullPointerException.package com.javaguides.corejava;
public class NullPointerExceptionExample {
public static void main(String[] args) {
Person personObj = null;
try {
String name = personObj.personName; // Accessing the field of a null object
personObj.personName = "Ramesh Fadatare"; // Modifying the field of a null object
} catch (NullPointerException e) {
System.err.println("NullPointerException caught!");
e.printStackTrace();
}
}
}
class Person {
public String personName;
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
}
NullPointerException caught!
java.lang.NullPointerException
at com.javaguides.corejava.NullPointerExceptionExample.main(NullPointerExceptionExample.java:9)
How to Avoid and Handle NullPointerException
Best Practices
- Always validate external data for null values.
- Favor returning empty collections (like Collections.emptyList()) or optional over null.
- Make use of Java's enhanced switch statement (from Java 14 onwards) which can handle null values.
- Clearly document if your methods return null or expect null parameters.
Comments
Post a Comment
Leave Comment