This Tutorial will explain all about the NullPointerException in Java. We will discuss the Causes of the Null Pointer Exception & ways to avoid it:
NullPointerException in Java is a runtime exception. Java assigns a special null value to an object reference. When a program tries to use an object reference set to the null value, then this exception is thrown.
=> Watch Out for The Simple Java Training Series Here.
Table of Contents:
NullPointerException In Java
If an object reference with a null value throws NullPointerException, then why do we need a null value?
The null value is usually used to indicate that no value has been assigned to a reference variable. Secondly, we need null values for collections like linked lists and trees to indicate null nodes. The design patterns like singleton patterns make use of null values.
To conclude, the null value in Java has many uses. Null Pointer Exception is thrown in specific scenarios in Java.
Some of the scenarios are as follows:
- Method invoked using a null object.
- Accessing or modifying a field or data member of the null object.
- Passing null object as an argument to a method.
- Calculating the length of a null array.
- Accessing the index of a null array.
- Synchronizing a null object.
- Throwing a null object.
The Null Pointer Exception extends from the class RuntimeException.
The hierarchy of NullPointerException is given below.
As shown in the above hierarchy, Null Pointer Exception extends from the RuntimeException that inherits the Exception Class. Exception class in turn is derived from the Throwable class that is a subclass of Object.
Causes Of java.lang.NullPointerException Occurrence
Now we will demonstrate each of the scenarios of NullPointerException occurrence that we listed above.
#1) The method is invoked using a null object
Consider the following code example. Here we have a class, MyClass that provides two methods. The first method ‘initT’ returns a null object. In the main method, we create an object of MyClass with a call to the initT method.
Next, we call the print method of MyClass. Here, the java.lang.NullPointerException is thrown as we are calling the print method using a null object.
class MyClass { public static MyClass initT() { //method returns a null object return null; } public void print(String s) { System.out.println(s.toLowerCase()); } } class Main{ public static void main(String[] args) { MyClass t = MyClass.initT(); //create a new object (null object) t.print("Hello, World!"); //invoke method using null object } }
Output
#2) Access the field of a null object
class MyClass { int numField = 100; public static MyClass initT() { //method returns a null object return null; } public void print(String s) { System.out.println(s.toLowerCase()); } } class Main{ public static void main(String[] args) { MyClass t = MyClass.initT(); //create a new object (null object) int num = t.numField; //access MyClass member using null object } }
Output
This is another cause of NullPointerException. Here we attempt to access a class member using a null object. We assign the return value of the initT method to the object t and then access numField using object t. But the object t is a null object as initT returns a null object. At this point, java.lang.NullPointerException is raised.
#3) Passing a null object as an argument
This is the common cause of java.lang.NullPointerException occurrence. Consider the following Java program. Here we have a method ‘print_LowerCase’ that converts the String object passed as an argument to a lowercase.
public class Main { public static void print_LowerCase(String s) { System.out.println(s.toLowerCase()); } public static void main(String[] args) { print_LowerCase(null); //pass null object as argument to the method } }
Output
In the main method, we call this method and pass a null as an argument. As the String object cannot be null, the java.lang.NullPointerException is thrown.
#4) Getting the length of a null array
Attempting to calculate the length of a null array also results in java.lang.NullPointerException being thrown.
The below program demonstrates this.
public class Main { public static void main(String[] args) { int[] dataArray = null; //Array is null; no data System.out.println("Array Length:" + dataArray.length); //print array length } }
Output
In the above program, we declare an array and assign null to it i.e. no data. When we use the length property on this null array, NullPointerException is thrown.
#5) Access the index of a null array
Similar to length, even if we try to access a value in a null array using an index, it is the cause of java.lang.NullPointerException.
public class Main { public static void main(String[] args) { int[] dataArray = null; //Array set to null //access value at index 2 System.out.println("Value at index 2:" + dataArray[2]); } }
Output
In the above program, we try to access the value at index 2 of a null array.
#6) Synchronization on a null object
We usually synchronize a block or a method to facilitate concurrent access. However, the object reference that we use for synchronization should not be null. If it is a null object, then it results in java.lang.NullPointerException.
The below Java program demonstrates this. As we can see, we have a String object ‘mutex’ initialized to null. Then in the main function, we use a synchronized block with mutex as the object reference. As mutex is null java.lang.NullPointerException is raised.
public class Main { public static String mutex = null; //mutex variable set to null public static void main(String[] args) { synchronized(mutex) { //synchronized block for null mutex System.out.println("synchronized block"); } } }
Output
#7) By throwing null
public class Main { public static void main(String[] args) { throw null; //throw null } }
Output:
In the above example program, instead of throwing a valid object, null is thrown. This results in Null Pointer Exception.
Avoiding Null Pointer Exception
Now that we have seen the causes of the occurrence of NullPointerException, we must also try to avoid it in our program.
First, we must ensure that the objects that we use in our programs are initialized properly so that we can avoid the use of null objects that result in a Null Pointer Exception. We should also take care that the reference variables used in the program are pointed to valid values and do not accidentally acquire null values.
Apart from these considerations, we can also exercise more caution on a case-by-case basis to avoid java.lang.NullPointerException.
Below we consider a few cases.
#1) String comparison with literals
A comparison between the string variable and a literal (actual value or element of the enum) is a very common operation in Java programs. But if the String variable that is an object is null, then comparing this null object to literals will throw NullPointerException.
So the solution is to invoke the comparison method from the literal instead of the String object that can be null.
The following program shows how we can invoke comparison methods from literals and avoid java.lang.NullPointerException.
class Main { public static void main (String[] args) { // String set to null String myStr = null; // Checking if myStr is null using try catch. try { if ("Hello".equals(myStr)) //use equals method with literal System.out.print("Two strings are same"); else System.out.print("Strings are not equal"); } catch(NullPointerException e) { System.out.print("Caught NullPointerException"); } } }
Output
#2) Keep a Check on the arguments of a method
Check the arguments of the method to ensure that they are not null values. If the arguments are not as per the specification, then the code will throw IllegalArgumentException to indicate that the arguments are not as expected.
This is shown in the below Java program.
import java.io.*; class Main { public static void main (String[] args) { // set String to empty value String myStr = ""; try { System.out.println("String value:" + myStr); System.out.println("String Length:" + getLength(myStr)); } catch(IllegalArgumentException e) { System.out.println("Exception: " + e.getMessage()); } // Set String to a proper value and call getLength myStr = "Far from home"; try { System.out.println("String value:" + myStr); System.out.println("String Length:" + getLength(myStr)); } catch(IllegalArgumentException e) { System.out.println("Exception: " + e.getMessage()); } // Set String to null and call getLength() myStr = null; try { System.out.println("String value:" + myStr); System.out.println("String Length:" + getLength(myStr)); } catch(IllegalArgumentException e) { System.out.println("Exception: " + e.getMessage()); } } // Method that returns length of the String public static int getLength(String myStr) { if (myStr == null) //throw Exception if String is null throw new IllegalArgumentException("The String argument cannot be null"); return myStr.length(); } }
Output
#3) Use of Ternary Operator to take care of null values
We can use the ternary operator to avoid java.lang.NullPointerException. The ternary operator has three operators. The first is a boolean expression that evaluates to true or false. If the expression is true, then the second operator is returned or the third operator is returned.
The following program shows the use of a ternary operator to avoid NullPointerException.
import java.io.*; class Main { public static void main (String[] args) { // Initialize String with null value String myStr = null; //return a substring for this String using ternary oprator String myVal = (myStr == null) ? "" : myStr.substring(0,5); if(myVal.equals("")) System.out.println("Empty String!!"); else System.out.println("String value: " + myVal); // Now set a value for String myStr = "SoftwareTestingHelp"; //return a substring for this String using ternary oprator myVal = (myStr == null) ? "" : myStr.substring(0,8); if(myVal.equals("")) System.out.println("Empty String!!"); else System.out.println("String value: " + myVal); }
Output
Frequently Asked Questions
How do I fix NullPointerException in Java?
We must ensure that all the objects used in the program are initialized properly and do not have null values. Also, the reference variables should not have null values.
Is NullPointerException checked or unchecked?
NullPointerException is not a checked exception. It is a descendant of RuntimeException and is unchecked.
How do I stop NullPointerException?
Some of the best practices to avoid NullPointerException are:
1. Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null.
2. Use valueOf() instead of toString() ; and both return the same result.
3. Use Java annotation @NotNull and @Nullable.
What is the null value in Java?
A null value does not refer to any object or variable. It is a keyword and a literal. It represents a null reference.
Can we catch NullPointerException in Java?
The exception java.lang.NullPointerException is an unchecked exception and extends the RuntimeException class. Hence there is no compulsion for the programmer to catch it.
Conclusion
In this tutorial, we have discussed the NullPointerException in Java. This is quite a dangerous exception and can usually pop up when we least expect it. Null Pointer Exception mostly occurs because of the null object or null reference. We have already seen the causes and ways to avoid NullPointerException.
As far as possible, the programmer should try to avoid the occurrence of a Null Pointer Exception in a program. As this is an unchecked runtime exception, we should see that it doesn’t occur when the application is running.
=> Visit Here To Learn Java From Scratch.