Avoiding NullPointerException in Java
A NullPointerException
is a runtime exception that is thrown when an application attempts to use an object reference that has a null value. To avoid this exception, you need to make sure that the object reference is not null before you use it.
Here are a few ways you can avoid a NullPointerException
in Java:
- Check for null: You can use an
if
statement to check if the object reference is null before you use it. If the object is null, you can either return or throw an exception, or assign a default value to the object. Here's an example of how you can check for null:
public class Main {
public static void main(String[] args) {
String str = null;
if (str != null) {
System.out.println(str.length());
} else {
System.out.println("str is null");
}
}
}
- Use the ternary operator: You can use the ternary operator (
? :
) to assign a default value to the object if it is null. The ternary operator is a conditional operator that evaluates a boolean expression and returns one value if the expression is true, and another value if the expression is false. Here's an example of how you can use the ternary operator to avoid aNullPointerException
:
public class Main {
public static void main(String[] args) {
String str = null;
int length = str != null ?