What is Java.lang.NullPointerException error and how to handle it

What is Java lang NullPointerException error?

In Java, the NullPointerException is a public class that extends the RuntimeExcpetion. The NullPointerException error is thrown in Java application or applet when you try to use a null object. The error occurs as you try to call the instance or method of an object which is null.

See a NullPointerException example online

For example, you have an integer object which value is null. Somewhere in your program, you tried to assign a value of that integer object to an int variable, then an error will be generated. The example below shows how this error generates.

This error also occurs when you try to access or modify the field of the null object.

Example of Java lang NullPointerException error when object value is null

The example below shows how NullPointerException Java error is generated when the integer object value is null.

The second example shows the error is not occurring as value is assigned to the integer object.

The NullPointerException



Experience this online

The output will be:

Exception in thread “main” java.lang.NullPointerException

at test_package.exception_example.main(exception_example.java:6)

Example of NullPointerException error resolved as null object is given a value



Experience this online

The output will be:

20

As you can see, when a value is assigned to the null object, the error is resolved.

Example of NullPointerException error as null object is accessed

The example below simply prints the integer object and it generates uncaught exception java.lang.nullpointerexception.

Java NullPointerException resolve



Experience this online

The output will be:

Exception in thread “main” java.lang.NullPointerException

at test_package.exception_example.main(exception_example.java:6)

Conclusion

The java.lang.NullPointerException error occurs as you call or access a null object. To avoid this error, you should carefully debug and assign the value to null objects before accessing it or assigning its value.

 

Also see: Exception handling by try-catch


Was this article helpful?

Related Articles

Leave A Comment?