In Java, the java.lang.NullPointerException is a popular exception that is faced by programmers while working on web applications and programs. The error is raised when the code tries to access a reference variable that points to a null value. It can be resolved by using an if-else condition or a try-catch block to check what the variable is pointing to.
Let’s dive deeper into the details of this error.
What is NullPointerException?
Null values are used in Java to not assign any value to a variable. The NullPointerException is a runtime error and is usually raised during the following scenarios –
- Calling a method from an object instance that is null during runtime
- Trying to modify or access a field of the null object
- Trying to determine the length of a null object as if it was an array
- Attempting to alter or access the index of an array that is null
- Throwing a null value in the program
Look at the code below –
Integer a;
a= new Integer(7);
In the first line, a variable a is declared but points to nothing. But in the second line, an object is created and the variable is pointing to the integer 7. But if you do not create an object and assign it to a variable, buy try to access it, the NullPointerException will be raised.
How to fix NullPointerException?
The following program will handle the error even if it is raised.
if(num ==null) num =" "; //This is an example of preventive coding
synchronized(num) {
System.out.println("synchronized block");
}
Ways to avoid NullPointerException
- To avoid the NullPointerException, always keep in mind that you have to initialize all variables properly before you attempt to use them
- Ensure that the methods you create return empty variables instead of null values
- Use methods such as contains(), containsValue() and containsKey() if you think the code might throw the error
- The ternary operator can be used –
String message = (str == null) ? " " : str.substring(0, str.length()-1);
- Use the String.valueOf() method instead of the toString() method –
Object rank = null;
System.out.println(String.valueOf(rank)); //prints null
System.out.println(rank.toString()); //throws NullPointerException
- Ensure that the arguments of the methods do not have null values
The methods described above will help you to fix and avoid the NullPointerException in your code. Apart from these pointers, make sure the external libraries you use do not return a reference containing a null value. You can read more about the methods to learn about their return values and functionalities.