The NullPointerException exception in Java
In Java, a NullPointerException is a common runtime exception that occurs when trying to access a member or method of an object with a null reference. In other words, it is the exception that happens when performing an operation on an object that is expected to be non-null.
Common situations involving NullPointerException include:
- Accessing or modifying member variables of a null object.
- Invoke a method on a null object.
- Accessing or modifying elements of an array that is null.
- Passing null as an argument to a method.
- Dereference the null pointer.
When a NullPointerException occurs, the Java virtual machine throws an exception and terminates the program’s execution. To prevent NullPointerException, you can check if the object reference is null before using the object, and ensure that the object reference is not null. This can be done by using conditional statements (such as if statements) or by using the null-safe operator (?.).
Here is an example that causes a NullPointerException:
String str = null;
System.out.println(str.length()); // NullPointerException
To avoid NullPointerException, null checks can be added in this example.
String str = null;
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("str is null");
}
By checking if the reference to an object is null, it can prevent NullPointerException and ensure the smooth execution of the program.