. Advertisement .
..3..
. Advertisement .
..4..
I am very confused, please help me to find the reason and how to fix the exception in thread “main” java.lang.nullpointerexception error:
Exception in thread "main" java.lang.NullPointerException
at NullPointerExceptionExample.printLength(NullPointerExceptionExample.java:3)
at NullPointerExceptionExample.main(NullPointerExceptionExample.java:8)
I am getting the above error while running the following code in Java:
public class NullPointerExceptionExample {
private static void printLength(String strName) {
System.out.println(strName.length());
}
public static void main(String args[]) {
String myStrName = null;
printLength(myStrName);
}
}
Looking forward to everyone’s guidance. Thanks.
The cause: The
NullPointerException
occurs when an uninitialized object is attempted to be accessed or updated in application code. This essentially signifies that the object reference has a null value and does not point anywhere.The command line causing the error is
System.out.println(strName.length());
strName
is not checked and you need to make sure that it is not empty before use.Solution: To resolve the NullPointerException in the example, the string
strName
should be verified for null or empty values before further use: