Dive deep into the NullPointerException exception in Java.
NullPointerException is one of the most common exceptions in Java, indicating that a program is trying to access a property of an object reference or call a method on an object reference that is currently null. If an object is created without a specific value assigned to it, the reference to that object is considered null. When a program tries to use a null object reference, a NullPointerException is thrown.
NullPointerException exceptions are typically caused by the following situations:
- Object not initialized: Attempting to access the properties or methods of an object that has not been initialized (i.e. not instantiated) will result in a NullPointerException exception.
String str;
System.out.println(str.length()); // 抛出NullPointerException异常
- Assigning null value to an object will result in a NullPointerException if an attempt is made to access its properties or methods.
String str = null;
System.out.println(str.length()); // 抛出NullPointerException异常
- When a method returns a null value, attempting to access its properties or methods will also result in a NullPointerException.
public String getName() {
return null;
}
String name = getName();
System.out.println(name.length()); // 抛出NullPointerException异常
To avoid the occurrence of a NullPointerException, you can perform a null check on the object before using it. Common ways to perform a null check include the following methods:
- Use if statements to check if the object is empty.
String str = null;
if (str != null) {
System.out.println(str.length()); // 判空后再使用对象
}
- Perform a null check on the object using the ternary operator.
String str = null;
int length = str != null ? str.length() : 0;
System.out.println(length);
- Perform null checks on objects using the Optional class introduced in Java 8.
String str = null;
Optional<String> optionalStr = Optional.ofNullable(str);
optionalStr.ifPresent(s -> System.out.println(s.length()));
In summary, a NullPointerException occurs when a program tries to access or manipulate a null reference object. To prevent this exception, it is recommended to perform a null check before using the object.