- How to Solve java.lang.NullPointerException Error
- What is java.lang.NullPointerException?
- Example of java.lang.NullPointer.Exception
- How to Fix java.lang.NullPointerException Error
- Check Your Code For Manual Errors
- Put Safety Checks Around Code That May Cause Null Pointer Exception
- Check For Null Before Accessing Something
- Conclusion
- How to Fix and Avoid NullPointerException in Java
- Why NullPointerException Occurs in Java
- NullPointerException Example
- How to Fix NullPointerException
- How to Avoid NullPointerException
- Track, Analyze and Manage Java Errors With Rollbar
How to Solve java.lang.NullPointerException Error
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.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
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:
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.
How to Fix and Avoid NullPointerException in Java
The java.lang.NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null.
Since the NullPointerException is a runtime exception, it doesn’t need to be caught and handled explicitly in application code.
Why NullPointerException Occurs in Java
The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.
Some of the most common scenarios for a NullPointerException are:
- Calling methods on a null object
- Accessing a null object’s properties
- Accessing an index element (like in an array) of a null object
- Passing null parameters to a method
- Incorrect configuration for dependency injection frameworks like Spring
- Using synchronized on a null object
- Throwing null from a method that throws an exception
NullPointerException Example
Here is an example of a NullPointerException thrown when the length() method of a null String object is called:
public class NullPointerExceptionExample < private static void printLength(String str) < System.out.println(str.length()); >public static void main(String args[]) < String myString = null; printLength(myString); >>
In this example, the printLength() method calls the length() method of a String without performing a null check prior to calling the method. Since the value of the string passed from the main() method is null, running the above code causes a NullPointerException :
Exception in thread "main" java.lang.NullPointerException at NullPointerExceptionExample.printLength(NullPointerExceptionExample.java:3) at NullPointerExceptionExample.main(NullPointerExceptionExample.java:8)
How to Fix NullPointerException
To fix the NullPointerException in the above example, the string should be checked for null or empty values before it is used any further:
import org.apache.commons.lang3.StringUtils; public class NullPointerExceptionExample < private static void printLength(String str) < if (StringUtils.isNotEmpty(str)) < System.out.println(str.length()); >else < System.out.println("Empty string"); >> public static void main(String args[]) < String myString = null; printLength(myString); >>
The code is updated with a check in the printLength() method that makes sure the string is not empty using the apache commons StringUtils.isNotEmpty() method. Only if the string is not empty the length() method of the string is called, else it prints the message Empty string to console.
How to Avoid NullPointerException
The NullPointerException can be avoided using checks and preventive techniques like the following:
- Making sure an object is initialized properly by adding a null check before referencing its methods or properties.
- Using Apache Commons StringUtils for String operations e.g. using StringUtils.isNotEmpty() for verifying if a string is empty before using it further.
- Using primitives rather than objects where possible, since they cannot have null references e.g. using int instead of Integer and boolean instead of Boolean .
Track, Analyze and Manage Java Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today!