How to fix java.lang.NullPointerException

Posted Under: JAVA, Programming, Tutorials on Nov 10, 2017
How to fix java.lang.NullPointerException
When programming in JAVA often developer see java.lang.NullPointerException. There are reasons as to why this Exception is thrown. So it is best to understand how to fix this exception before the application is deployed in production.

Null Pointer Exception is thrown when the program is trying to memory location that do not exist. This happen to usually when trying to call an instance with out initializing it. Or accessing an instance's member that do not exists or private. NULL Pointer exception are also thrown by the JVM if someone tries to take the length of an array that was not initialized. Furthermore this exception can also be thrown explicitly by a program to indicate other illegal uses of the null objects.

How to Fix java.lang.NullPointerException

  • Identify the NULL values, First identify the NULL values that are responsible for throwing this Exception. This is can be done by looking at the the stack trace of the program or the Exception message. This will narrow done your search.
  • Trace the origin of these values. Find from where the values are coming and how they were assigned. It may be condition that hinders the assigning or execution of that statement. If it is method param trace the caller and debug what is sent to invoke that method.
  • Default Values. Always try to assign a default value to be on safe side to avoid NULL pointer exception.
  • Avoid Using !=null. Because NULL can be a desired value in some case.
  • Testing Test your code hard so that it work smooth.