NullPointerException – Eg 1 When Instance of an Object Is set to Null and It Is Used as A reference

java.lang.NullPointerException exception is one of the most popular errors in Java and it is caused by so many issues.

One of such issues is when an objected is initiated to a Null value and then its reference is used to call a method or a variable.

Example is in the code below.

In the code above the line at

throws java.lang.NullPointerException because the doSomething() method sets the CheckingNullPointers instance to Null and then the Null instance is being used to call setField2(String field2) which then throws the exception. 

It is always good to check if the instance is not Null before using it to call a method or variable.

 

Want more information like this?

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *