You must have come across something called a NullPointerException if you have worked on Java-based applications. The Null Pointer Exception is one of the most common errors in Java application development. This exception is usually the result of a human error, buttime can get wasted on debugging errors like this one. This issue is not entirely a syntactical error, so it can get tricky to identify the problem at times.
In this article, we take a look at what java.lang.NullPointerException is, why does it happen, how you can fix it, and some of the best practices to follow to avoid running into wild null pointers. Without further ado, let’s begin.
What is java.lang.NullPointerException?
The Null Pointer Exception is one of the several Exceptions supported by the Java language. This indicates that an attempt has been made to access a reference variable that currently points to null.
Null is the default value in Java assigned to the variables which are not initialized by the user after or with a declaration. Consider the following example where you declare a variable like this:
String str;
And then try to print the contents of the variable:
System.out.println(str); // => null
As can be seen above, ‘null’ gets printed on the output. This shows that since the variable str is uninitialized, it currently points to, or holds the value, null. The issue that a null pointing variable poses is that the variable is only a reference, and it does not point to anything. If you try to carry out some operations on the data stored in a null pointing variable, the system will not know what to do. This happens because there is no data actually stored in the variable; it points to a void entity.
Example of java.lang.NullPointer.Exception
Looking for examples of java.lang.NullPointerException is not a difficult task, as all you need to do is not initialize a variable before trying to access it. For instance, let’s consider the StringBuilder class. StringBuilder is a class that is used to handle the formation and manipulation of strings. Here’s how you would normally use the class to create strings:
import java.util.StringBuilder; public class Test { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello "); sb.append("World!"); String result = sb.toString(); System.out.println(result); // => Hello World! } }
If you run the above snippet, it will work just fine. Let’s take a look at its modified version that will throw a null pointer exception:
import java.util.StringBuilder; public class Test { public static void main(String[] args) { StringBuilder sb; sb.append("Hello "); sb.append("World!"); String result = sb.toString(); System.out.println(result); } }
As you can see, we did not initialize an instance of the StringBuilder class while declaring it. When the sb.append()
lines are executed, sb does not point to any object in reality, rather it points to null. This is where a NullPointerException gets thrown. Due to the exception being thrown, the JVM cannot execute any statements after this.
How to Fix java.lang.NullPointerException Error
Creating a Null Pointer Exception is easy, but avoiding or fixing it is tricky. While some integrated development environments (IDEs) warn you if you are accessing a variable before initializing it with some compatible value, most IDEs can not figure this out in complex situations, such as when passing a variable through multiple method calls. The exact fix for a Null Pointer Exception depends upon your situation and code. Here are some of the top ways to fix common Null Pointer scenarios:
Check Your Code For Manual Errors
The biggest reason why Null Pointer Exceptions occur is human error. Make sure the program you have written carries the correct logic that you had initially intended. Also, run your eyes through the source code to check if you have missed out any statements, or misspelled any variables which may have led to some variable not being assigned a value.
Ensure that you have written your code the way your logic directs you to, and you have not missed out on writing any statements, or have not assigned objects to wrong references. As a rule of thumb, check that before any variable is used, it is initialized with an object.
Put Safety Checks Around Code That May Cause Null Pointer Exception
If you know the line of code that is causing your NullPointer and believe your logic is correct as well, you can wrap the section of code in a try-catch block, and define the behavior for when a Null Pointer is caught. This is how such a set-up will look like:
... // Some code above try { // Put the exception-prone code here } catch (NullPointerException npe) { // Define what needs to be done when an NPE is caught } // Some code below ...
This happens in situations where a certain reference variable may or may not contain null. More often than not, remote API responses, device interface responses are prone to this scenario. Depending upon the availability of a result or hardware, the response variable may or may not point to an instantiated object. Using safety checks is best-suited to handle these situations.
Check For Null Before Accessing Something
This method is similar to the try-catch method. In this method, an ‘if’ block is used to check for null values before accessing a variable. Here’s how the previous snippet of code would look like if an ‘if’ block is used to catch the error:
... // Some code above If (myVar !== null ) { // Put the success logic here } else { // Handle null value here } // Some code below ...
The biggest difference between the two methods is the scope of checks that they do. The if method checks the myVar variable only for null values, while the try-catch block catches any and all variables that are null.
This makes the ‘if’ block a more targeted and clean approach to accommodating null pointers in your application logic. However, if there is more than one variable that may be null, it is better to go with a try-catch block for simplicity.
Conclusion
This article took a look at what Null Pointer Exception is in Java, and how this error occurs. We also looked at a piece of code that will cause a Null Pointer Exception to understand how Null Pointers are created in real-life situations. Finally, we set down to identify some of the top ways to fix a Null Pointer Exception and ended our discussion by contrasting between two methods of fixing NPEs.
If you are looking to write Java programs, a Null Pointer Exception is one of the essential bugs that you must know how to fix. This exception is one of the most frequent issues and is not related to your code’s syntax or semantics. This makes the exception one of the trickiest problems to identify and fix. A quick reference for fixing the issue like this article is bound to make your experience smoother.
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.