In this Java tutorial, you will learn when java.lang.NullPointerException occurs, and how to handle this exception.

What is NullPointerException in Java?

java.lang.NullPointerException occurs during runtime when a method of an object, belonging to a class is invoked, given the object value is null. In this java tutorial, we shall see how a NullPointerException occurs and the ways to handle java.lang.NullPointerException.

Example

1. Recreate NullPointerException

In this example, we will recreate NullPointerException by calling a method/routine on an object which is having **null** value.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args) {
		String words = null;
		String[] wordArray = words.split("\t");
		for(String word:wordArray){
			System.out.println(word);
		}
	}
}

When the program is run, we get a NullPointerException at line words.split(“\t”), where the value of words is null. The output is shown below:

Exception in thread "main" java.lang.NullPointerException
	at com.tut.NullPointerExceptionExample.main(NullPointerExceptionExample.java:10)

How to handle java.lang.NullPointerException ?

Top handle this NullPointerException, do a null check for the object before accessing the methods/routines/behaviors of it.

Examples

1. Handle NullPointerException using Null Check

In the following example, before calling split() method on words array, we are checking if words object is not null using if statement.

Example.java

</>
Copy
package com.tut;

/**
 * @author arjun
 */
public class Example {

	public static void main(String[] args) {
		String words = null;

		String[] wordArray = null;
		if(words!=null){
			wordArray = words.split("\t");
		}
		if(wordArray!=null){
			for(String word:wordArray){
				System.out.println(word);
			}
		}
		System.out.println("Program handles NullPointerException.");
	}
}

Even though, the code above is a dead code, it still demonstrates to first check if an object is null, and then proceed with accessing its methods. When the code is run, the output is as shown in the following.

Output

Program handles NullPointerException.

2. Handle NullPointerException using Try-Catch

Or, you can use Try-Catch block around the code snippet that has the potential to throw NullPointerException.

Example.java

</>
Copy
public class Example {
	public static void main(String[] args) {
		String words = null;
		String[] wordArray = null;

		try {
			wordArray = words.split("\t");
			for(String word:wordArray){
				System.out.println(word);
			}
		} catch (NullPointerException e) {
			System.out.println("NullPointerException caught.");
		}
	}
}

Here, we used a try-catch block to handle NullPointerException. String.split() operation can throw NullPointerException if the given string is null.

Output

NullPointerException caught.

Conclusion

In this Java Tutorial, we learned what NullPointerException is and how we handle java.lang.NullPointerException.