Exceptions are helpful in the smooth running of code and allow the programmers the errors that need to be solved. Today, we will focus on the Null pointer exception in Java.
NullPointerException in java occurs when a java program attempts to use an object reference that has the null value. In the Java world, you can assign a null value to an object reference.
What is Null Pointer Exception in Java?
The Null pointer exception in Java i.e java.lang.NullPointerException is a kind of Runtime exception that occurs when you try to access a variable that doesn’t point to any object and refers to nothing or null. The Null Pointer Exception in Java doesn’t necessarily be caught and handled in the application code.
Source: ATechDaily
What Causes NullPointer Exception?
The null pointer exception in a java program occurs when you try to access or modify an uninitialized object. This is a special situation in the application code.
Following are the most common situations for the java null pointer exception occurrence.
- When null parameters are passed on to a method.
- Trying to access the properties or an index element of a null object.
- Calling methods on a null object.
- Following incorrect configuration for dependency injection frameworks such as Spring.
NullPointer Exception Example
Here is an example of NullPointerException in java that is thrown when you call a length() method of a null String object.
In the above example, the length() method of string is called by the printLength() method without performing a null check before calling the method. As the value of the string passed from the main() method is null, the above code results in a NullPointerException:
How to Fix NullPointer Exception?
To fix Null pointer exception in java programming, you should check the string for empty or null 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); } }
In order to fix the java.lang.NullPointException, the printLength() method in the above code is updated with a check that ensures that the string parameter is not empty using the StringUtils.isNotEmpty() method. If the string parameter is empty it prints the message “Empty String” to the console and if the string is not empty the length() method of the string is called.
How to avoid the NullPointer Exception in Java Programming?
To avoid NullPointerException in java programming, always make sure that all the objects are properly initialized before you use them. Before invoking a method on an object, verify that the object is not null while declaring a reference variable.
Given below are some null pointer exception problems with solutions.
1. String Comparison With Literals
The most common null pointer exception problems involve a comparison between a history variable and a literal that may be a string or an element of Enum. Consider invoking the method from the literal rather than invoking it from the null object.
// A Java program to demonstrate that invoking a method on null // causes NullPointerException import java.io.*; class GFG { public static void main (String[] args) { // Initializing String variable with null value String ptr = null; // Checking if ptr.equals null or works fine. try { // This line of code throws NullPointerException, because ptr is null if (ptr.equals("gfg")) System.out.print("Same"); else System.out.print("Not Same"); } catch(NullPointerException e) { System.out.print("NullPointerException Caught"); } } }
Output:
NullPointerException Caught
In this case, NullPointerException can be avoided by calling equals on literal instead of calling object.
// A Java program to demonstrate that we can avoid // NullPointerException import java.io.*; class GFG { public static void main (String[] args) { // Initialing String variable with null value String ptr = null; // Checking if ptr is null using try catch. try { if ("gfg".equals(ptr)) System.out.print("Same"); else System.out.print("Not Same"); } catch(NullPointerException e) { System.out.print("Caught NullPointerException"); } } }
Output:
Not Same
2. Use of Ternary Operator
You can use a ternary operator to avoid a NullPointerException. First of all the Boolean expression is evaluated for the true or false results. If the expression is true then the value true is returned and if it is wrong the value false is returned. Ternary operator can be used to handle null pointer exceptions in java.
// A Java program to demonstrate that we can use // ternary operator to avoid NullPointerException. import java.io.*; class GFG { public static void main (String[] args) { // Initializing message variable with non-null value String str = null; String message = (str == null) ? "" : str; System.out.println(message); // Initializing message variable with non-null value str = "Seagence"; message = (str == null) ? "" : str; System.out.println(message); } }
Output:
Seagence
3. Keeping a Check of the Arguments of a Method
Always ensure the arguments of the new method for non-null before executing the body of the new method and continue with the method execution, only when the arguments are properly checked. Or else, it will return an IllegalArgumentException and notifies the calling method that something isn’t right with arguments passed.
// A Java program to demonstrate that we should // check if parameters are null or not before // using them. import java.io.*; class GFG { public static void main (String[] args) { // String s set an empty string and calling getLength() String s = ""; try { System.out.println(getLength(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); } // String s set to a value and calling getLength() s = "GeeksforGeeks"; try { System.out.println(getLength(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); } // Setting s as null and calling getLength() s = null; try { System.out.println(getLength(s)); } catch(IllegalArgumentException e) { System.out.println("IllegalArgumentException caught"); } } // Function to return length of string s. It throws // IllegalArgumentException if s is null. public static int getLength(String s) { if (s == null) throw new IllegalArgumentException("The argument cannot be null"); return s.length(); } }
Output:
0
13
IllegalArgumentException caught
To avoid Null point Exceptions, you need to take care that all objects are initialized with a legitimate value (that is not null), before using them. As any operation performed on a null reference variable will lead to the NullPointerException, at the time of defining, it must be verified that the reference variable is not null.
Conclusion
Avoiding and fixing null point exceptions is an important task for the developers in Java. Unlike many other programming languages, Java doesn’t provide any methods to check null pointer exceptions.
That’s why developers need additional tools that can help them prevent NullPointerException in java. Seagence is one such tool that automates Java error management, prioritizing the errors, making the process of error fixing easier than ever. Try Seagence free today! Click here to know more.