What is NullPointerException in Java: Explanation and Example
NullPointerException in Java is an error that happens when your program tries to use an object reference that points to null, meaning no actual object exists there. It usually occurs when you call a method or access a field on a null reference.How It Works
Imagine you have a remote control but no TV connected to it. Trying to change the channel with that remote is like calling a method on a null object in Java. The remote (object reference) exists, but it doesn't point to any TV (actual object), so the action fails.
In Java, when you declare an object variable but don't assign it an actual object, it holds the value null. If you try to use this variable to access methods or properties, Java throws a NullPointerException because there is no real object to work with.
Example
NullPointerException caused by calling a method on a null reference.public class NullPointerExample { public static void main(String[] args) { String text = null; // text points to nothing System.out.println(text.length()); // Trying to get length causes NullPointerException } }
When to Use
You don't "use" a NullPointerException intentionally; it is an error to avoid. Understanding it helps you write safer code by checking if objects are null before using them. For example, when working with data that might be missing or optional, you should verify the object exists to prevent this exception.
In real-world programs, this exception often appears when dealing with user input, database results, or external data sources where some values might be missing.
Key Points
- NullPointerException happens when calling a method or accessing a field on a
nullreference. - It is a runtime error that stops the program unless handled.
- Always check if an object is
nullbefore using it to avoid this exception. - Using modern Java features like
Optionalcan help managenullvalues safely.