What is a NullPointerException, and How to Fix it?

What is a NullPointerException?

When you try to use a reference that points to no location in memory (null) as if it were addressing an object, you get a NullPointerException. A NullPointerException is thrown when a method is called on a null reference or when a field of a null reference is read. The most frequent are listed in the NullPointerException javadoc page, however there are others.

How to Fix it?

So you have a NullPointerException. How do you fix it? Let’s take an example which throws a NullPointerException:

public class Printer {
    private String Username;

    public void setName(String Username) {
        this.Username= Username;

    public void print() {

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");

    public static void main(String[] args) {
        Printer printer = new Printer();

Identify the null values

The first step is to figure out which values are creating the problem. We’ll need to conduct some debugging for this. It’s critical to understand how to interpret a stacktrace. You may see where the exception was thrown by looking at this:

Exception in thread "main" java.lang.NullPointerException
    at Printer.printString(Printer.java:13)
    at Printer.print(Printer.java:9)
    at Printer.main(Printer.java:19)

Read the error message carefully as you can see the error is at line 13. Trace where this value comes from. By following the callers of the method, we see that s is passed in with printString(Username) in the print() method, and this.Username is null.

You can also fix NullPointerException by one of the following solutions:

By initializing variable.

private String Username = "";

Checking the variable, if its null

printString((Username == null) ? "" : name);

Author Images
From Islamabad

A software developer with a keen interest in writing about technology, finance, and entrepreneurship. I've written for businesses in a variety of fields, including new technology, healthcare, programming, consumer applications, corporate computing, UI/UX, outsourcing, and education.

Post a comment

Your email address will not be published. Required fields are marked *

    Press x to close