In this Java tutorial, you will learn what java.lang.NullPointerException means, what causes it, how to read the error line in the stack trace, and how to handle or prevent it with safe Java code.

What is java.lang.NullPointerException in Java?

java.lang.NullPointerException is a runtime exception thrown when Java code tries to use a reference variable that currently points to null as though it points to a real object. A null value means no object is available at that reference. Therefore, Java cannot call an instance method, read an instance field, write an instance field, or use array operations on it.

NullPointerException is unchecked, so the compiler does not force you to catch it. The usual fix is not to catch it everywhere, but to find why the value became null and either initialize it, validate it, or handle the missing value before using it.

Common causes of NullPointerException in Java code

A NullPointerException usually happens in one of these situations:

  • Calling a method on a null object reference, such as words.split("\t") when words is null.
  • Accessing an instance field on a null object.
  • Finding the length of a null array or reading an element from a null array.
  • Auto-unboxing a null wrapper object, such as assigning a null Integer to an int.
  • Using a returned value without checking whether the method can return null.
  • Passing null to code that does not accept it.

Example: recreate NullPointerException by calling a method on null

In this example, we will recreate NullPointerException by calling a method on an object reference whose value is null.

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, Java throws a NullPointerException at the line words.split("\t"), because words is null. The output is shown below:

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

In newer Java versions, the message may also include a more detailed explanation, such as which variable was null. Even then, the fixing process is the same: identify the null reference, then decide whether it should be initialized, rejected, or handled as an optional missing value.

How to read a NullPointerException stack trace in Java

A stack trace tells you where the exception happened. Start with the first line in your own code, not with library or framework lines. In the example above, the important part is:

at com.tut.NullPointerExceptionExample.main(NullPointerExceptionExample.java:10)

This means the exception occurred in the main method of NullPointerExceptionExample.java at line 10. Open that line and check every reference used on the line. In words.split("\t"), the reference before the dot is words, so words is the value to inspect first.

How to handle java.lang.NullPointerException safely

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

For production code, prefer preventing the null reference before it reaches the failing line. A local null check is useful, but it should express the real business rule: should a missing value be skipped, replaced with a default value, or treated as an invalid input?

1. Handle NullPointerException using a null check before split()

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 only when recovery is possible

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.

Use this approach carefully. Catching NullPointerException can hide a programming error if the catch block only prints a message and continues. It is more useful when the program can genuinely recover, log a clear error, or return a safe response to the caller.

3. Prevent NullPointerException with a default empty string

If a null string should be treated as empty input, assign a default value before calling methods on it. This keeps the rest of the code simple and avoids repeated null checks.

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

        String safeWords = (words == null) ? "" : words;
        String[] wordArray = safeWords.split("\t");

        System.out.println("Number of words: " + wordArray.length);
    }
}

Output

Number of words: 1

This is appropriate only when an empty value is meaningful for your program. If the value is required, do not silently replace it; validate it and fail with a clear message.

4. Fail early with Objects.requireNonNull()

When a value must not be null, Objects.requireNonNull() makes that rule explicit. It still throws a NullPointerException, but it does so at the boundary where the invalid value enters the method, with a clearer message.

</>
Copy
import java.util.Objects;

public class Example {
    static String[] splitWords(String words) {
        Objects.requireNonNull(words, "words must not be null");
        return words.split("\t");
    }

    public static void main(String[] args) {
        splitWords(null);
    }
}

This pattern is useful in constructors, service methods, and utility methods where a null argument indicates a caller error.

NullPointerException prevention patterns for everyday Java programs

  • Initialize variables before use: avoid leaving object references as null when a real default object makes sense.
  • Check method return values: if a method can return null, document it and check the result before calling methods on it.
  • Validate required parameters: use clear guard clauses at the beginning of a method.
  • Use safe equality checks: write "admin".equals(role) instead of role.equals("admin") when role might be null.
  • Avoid unnecessary nulls in collections: prefer empty lists, empty maps, or empty arrays when “no values” is a valid result.
  • Use Optional for return values when suitable: Optional can show that a value may be absent, but it should not be used for every field or parameter.

Choosing between null check, try-catch, default value, and fail-fast validation

SituationBetter approachReason
The value is optional and missing values are allowed.Use a null check or default value.The program has a defined path for missing data.
The value is required for the method to work.Validate early with a guard clause or Objects.requireNonNull().The error is reported near the source of the invalid input.
A third-party API unexpectedly returns null.Check the returned value before use.Your code should protect itself at integration boundaries.
You can recover from the failure.Use try-catch with a meaningful recovery action.The catch block should do more than hide the bug.
The exception reveals a programming mistake.Fix the initialization or logic that created the null.Suppressing the exception can make later errors harder to debug.

FAQ on java.lang.NullPointerException handling

How to handle null pointer in Java?

Handle a null pointer in Java by checking whether the reference is null before using it, assigning a meaningful default value, validating required parameters, or changing the method design so it does not return null unexpectedly. Use try-catch only when the program has a real recovery action.

What causes a NullPointerException in Java?

A NullPointerException is caused when code uses null like an object. Common examples include calling a method on null, reading a field from null, using a null array, auto-unboxing a null wrapper value, or using a null return value without checking it.

How to stop NullPointerException in Java?

Stop NullPointerException by tracing the stack trace to the failing line, identifying which reference is null, and fixing the source of that null. In many cases, this means initializing the object, adding input validation, returning an empty collection instead of null, or handling missing values before method calls.

Is it good practice to catch NullPointerException?

It is usually better to prevent NullPointerException than to catch it. Catching it may be acceptable at a boundary layer, such as request handling or logging, but using catch blocks as a substitute for null-safe logic can hide bugs.

Can String.split() throw NullPointerException?

String.split() itself works on a valid string object. The NullPointerException occurs when the string reference used to call split() is null, as in words.split("\t") when words is null.

NullPointerException tutorial QA checklist

  • Does the tutorial explain that NullPointerException is a runtime exception caused by using a null reference as an object?
  • Does the stack trace explanation point readers to the exact file and line where the null reference is used?
  • Do the examples show both prevention with null checks and handling with try-catch?
  • Does the article warn that catching NullPointerException can hide programming errors?
  • Are all Java examples formatted with PrismJS-compatible language classes?

Conclusion

In this Java Tutorial, we learned what NullPointerException is and how we handle java.lang.NullPointerException. The safest approach is to read the stack trace, identify the null reference, and then choose the right fix: initialize the object, validate required input, use a meaningful default value, or catch the exception only when recovery is possible.