Как исправить ошибку internal exception java lang nullpointerexception

What are Null Pointer Exceptions (java.lang.NullPointerException) and what causes them? What methods/tools can be used to determine the cause so that you stop the exception from causing the progra...

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying «no object».

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled «HERE» is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception … but the standard javac compiler doesn’t.)

Second observation: when I run the program, it outputs two lines of «gobbledy-gook». WRONG!! That’s not gobbledy-gook. It is a stacktrace … and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let’s look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be «main». Let’s move on …
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • «at Test.main» says that we were in the main method of the Test class.
  • «Test.java:4» gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the «HERE» comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first «at» line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

See also: What is a stack trace, and how can I use it to debug my application errors?

1 — Not quite true. There are things called nested exceptions…

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let’s illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and… BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first «at» line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second «at» line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let’s try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two «at» lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null … but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo … so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying «no object».

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled «HERE» is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception … but the standard javac compiler doesn’t.)

Second observation: when I run the program, it outputs two lines of «gobbledy-gook». WRONG!! That’s not gobbledy-gook. It is a stacktrace … and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let’s look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be «main». Let’s move on …
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • «at Test.main» says that we were in the main method of the Test class.
  • «Test.java:4» gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the «HERE» comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first «at» line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

See also: What is a stack trace, and how can I use it to debug my application errors?

1 — Not quite true. There are things called nested exceptions…

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let’s illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and… BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first «at» line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second «at» line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let’s try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two «at» lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null … but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo … so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

Question: What causes a NullPointerException (NPE)?

As you should know, Java types are divided into primitive types (boolean, int, etc.) and reference types. Reference types in Java allow you to use the special value null which is the Java way of saying «no object».

A NullPointerException is thrown at runtime whenever your program attempts to use a null as if it was a real reference. For example, if you write this:

public class Test {
    public static void main(String[] args) {
        String foo = null;
        int length = foo.length();   // HERE
    }
}

the statement labeled «HERE» is going to attempt to run the length() method on a null reference, and this will throw a NullPointerException.

There are many ways that you could use a null value that will result in a NullPointerException. In fact, the only things that you can do with a null without causing an NPE are:

  • assign it to a reference variable or read it from a reference variable,
  • assign it to an array element or read it from an array element (provided that array reference itself is non-null!),
  • pass it as a parameter or return it as a result, or
  • test it using the == or != operators, or instanceof.

Question: How do I read the NPE stacktrace?

Suppose that I compile and run the program above:

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.main(Test.java:4)
$

First observation: the compilation succeeds! The problem in the program is NOT a compilation error. It is a runtime error. (Some IDEs may warn your program will always throw an exception … but the standard javac compiler doesn’t.)

Second observation: when I run the program, it outputs two lines of «gobbledy-gook». WRONG!! That’s not gobbledy-gook. It is a stacktrace … and it provides vital information that will help you track down the error in your code if you take the time to read it carefully.

So let’s look at what it says:

Exception in thread "main" java.lang.NullPointerException

The first line of the stack trace tells you a number of things:

  • It tells you the name of the Java thread in which the exception was thrown. For a simple program with one thread (like this one), it will be «main». Let’s move on …
  • It tells you the full name of the exception that was thrown; i.e. java.lang.NullPointerException.
  • If the exception has an associated error message, that will be output after the exception name. NullPointerException is unusual in this respect, because it rarely has an error message.

The second line is the most important one in diagnosing an NPE.

at Test.main(Test.java:4)

This tells us a number of things:

  • «at Test.main» says that we were in the main method of the Test class.
  • «Test.java:4» gives the source filename of the class, AND it tells us that the statement where this occurred is in line 4 of the file.

If you count the lines in the file above, line 4 is the one that I labeled with the «HERE» comment.

Note that in a more complicated example, there will be lots of lines in the NPE stack trace. But you can be sure that the second line (the first «at» line) will tell you where the NPE was thrown1.

In short, the stack trace will tell us unambiguously which statement of the program has thrown the NPE.

See also: What is a stack trace, and how can I use it to debug my application errors?

1 — Not quite true. There are things called nested exceptions…

Question: How do I track down the cause of the NPE exception in my code?

This is the hard part. The short answer is to apply logical inference to the evidence provided by the stack trace, the source code, and the relevant API documentation.

Let’s illustrate with the simple example (above) first. We start by looking at the line that the stack trace has told us is where the NPE happened:

int length = foo.length(); // HERE

How can that throw an NPE?

In fact, there is only one way: it can only happen if foo has the value null. We then try to run the length() method on null and… BANG!

But (I hear you say) what if the NPE was thrown inside the length() method call?

Well, if that happened, the stack trace would look different. The first «at» line would say that the exception was thrown in some line in the java.lang.String class and line 4 of Test.java would be the second «at» line.

So where did that null come from? In this case, it is obvious, and it is obvious what we need to do to fix it. (Assign a non-null value to foo.)

OK, so let’s try a slightly more tricky example. This will require some logical deduction.

public class Test {

    private static String[] foo = new String[2];

    private static int test(String[] bar, int pos) {
        return bar[pos].length();
    }

    public static void main(String[] args) {
        int length = test(foo, 1);
    }
}

$ javac Test.java 
$ java Test
Exception in thread "main" java.lang.NullPointerException
    at Test.test(Test.java:6)
    at Test.main(Test.java:10)
$ 

So now we have two «at» lines. The first one is for this line:

return args[pos].length();

and the second one is for this line:

int length = test(foo, 1);
    

Looking at the first line, how could that throw an NPE? There are two ways:

  • If the value of bar is null then bar[pos] will throw an NPE.
  • If the value of bar[pos] is null then calling length() on it will throw an NPE.

Next, we need to figure out which of those scenarios explains what is actually happening. We will start by exploring the first one:

Where does bar come from? It is a parameter to the test method call, and if we look at how test was called, we can see that it comes from the foo static variable. In addition, we can see clearly that we initialized foo to a non-null value. That is sufficient to tentatively dismiss this explanation. (In theory, something else could change foo to null … but that is not happening here.)

So what about our second scenario? Well, we can see that pos is 1, so that means that foo[1] must be null. Is this possible?

Indeed it is! And that is the problem. When we initialize like this:

private static String[] foo = new String[2];

we allocate a String[] with two elements that are initialized to null. After that, we have not changed the contents of foo … so foo[1] will still be null.

What about on Android?

On Android, tracking down the immediate cause of an NPE is a bit simpler. The exception message will typically tell you the (compile time) type of the null reference you are using and the method you were attempting to call when the NPE was thrown. This simplifies the process of pinpointing the immediate cause.

But on the flipside, Android has some common platform-specific causes for NPEs. A very common is when getViewById unexpectedly returns a null. My advice would be to search for Q&As about the cause of the unexpected null return value.

Довольно часто при разработке на Java программисты сталкиваются с NullPointerException, появляющимся в самых неожиданных местах. В этой статье мы разберёмся, как это исправить и как стараться избегать появления NPE в будущем.

NullPointerException (оно же NPE) это исключение, которое выбрасывается каждый раз, когда вы обращаетесь к методу или полю объекта по ссылке, которая равна null. Разберём простой пример:

Integer n1 = null;
System.out.println(n1.toString());

Здесь на первой строке мы объявили переменную типа Integer и присвоили ей значение null (то есть переменная не указывает ни на какой существующий объект).
На второй строке мы обращаемся к методу toString переменной n1. Так как переменная равна null, метод не может выполниться (переменная не указывает ни на какой реальный объект), генерируется исключение NullPointerException:

Exception in thread "main" java.lang.NullPointerException
	at ru.javalessons.errors.NPEExample.main(NPEExample.java:6)

Как исправить NullPointerException

В нашем простейшем примере мы можем исправить NPE, присвоив переменной n1 какой-либо объект (то есть не null):

Integer n1 = 16;
System.out.println(n1.toString());

Теперь не будет исключения при доступе к методу toString и наша программа отработает корректно.

Если ваша программа упала из-за исключение NullPointerException (или вы перехватили его где-либо), вам нужно определить по стектрейсу, какая строка исходного кода стала причиной появления этого исключения. Иногда причина локализуется и исправляется очень быстро, в нетривиальных случаях вам нужно определять, где ранее по коду присваивается значение null.

Иногда вам требуется использовать отладку и пошагово проходить программу, чтобы определить источник NPE.

Как избегать исключения NullPointerException

Существует множество техник и инструментов для того, чтобы избегать появления NullPointerException. Рассмотрим наиболее популярные из них.

Проверяйте на null все объекты, которые создаются не вами

Если объект создаётся не вами, иногда его стоит проверять на null, чтобы избегать ситуаций с NullPinterException. Здесь главное определить для себя рамки, в которых объект считается «корректным» и ещё «некорректным» (то есть невалидированным).

Не верьте входящим данным

Если вы получаете на вход данные из чужого источника (ответ из какого-то внешнего сервиса, чтение из файла, ввод данных пользователем), не верьте этим данным. Этот принцип применяется более широко, чем просто выявление ошибок NPE, но выявлять NPE на этом этапе можно и нужно. Проверяйте объекты на null. В более широком смысле проверяйте данные на корректность, и консистентность.

Возвращайте существующие объекты, а не null

Если вы создаёте метод, который возвращает коллекцию объектов – не возвращайте null, возвращайте пустую коллекцию. Если вы возвращаете один объект – иногда удобно пользоваться классом Optional (появился в Java 8).

Заключение

В этой статье мы рассказали, как исправлять ситуации с NullPointerException и как эффективно предотвращать такие ситуации при разработке программ.

Ряд пользователей (да и разработчиков) программных продуктов на языке Java могут столкнуться с ошибкой java.lang.nullpointerexception (сокращённо NPE), при возникновении которой запущенная программа прекращает свою работу. Обычно это связано с некорректно написанным телом какой-либо программы на Java, требуя от разработчиков соответствующих действий для исправления проблемы. В этом материале я расскажу, что это за ошибка, какова её специфика, а также поясню, как исправить ошибку java.lang.nullpointerexception.

Ошибка java.lang.nullpointerexception

Содержание

  1. Что это за ошибка java.lang.nullpointerexception
  2. Как исправить ошибку java.lang.nullpointerexception
  3. Для пользователей
  4. Для разработчиков
  5. Заключение

Что это за ошибка java.lang.nullpointerexception

Появление данной ошибки знаменует собой ситуацию, при которой разработчик программы пытается вызвать метод по нулевой ссылке на объект. В тексте сообщения об ошибке система обычно указывает stack trace и номер строки, в которой возникла ошибка, по которым проблему будет легко отследить.

Номер строки с ошибкой

Что в отношении обычных пользователей, то появление ошибки java.lang.nullpointerexception у вас на ПК сигнализирует, что у вас что-то не так с функционалом пакетом Java на вашем компьютере, или что программа (или онлайн-приложение), работающие на Java, функционируют не совсем корректно. Если у вас возникает проблема, при которой Java апплет не загружен, рекомендую изучить материал по ссылке.

Скриншот ошибки Java

Как исправить ошибку java.lang.nullpointerexception

Как избавиться от ошибки java.lang.nullpointerexception? Способы борьбы с проблемой можно разделить на две основные группы – для пользователей и для разработчиков.

Для пользователей

Если вы встретились с данной ошибкой во время запуска (или работы) какой-либо программы (особенно это касается minecraft), то рекомендую выполнить следующее:

  1. Переустановите пакет Java на своём компьютере. Скачать пакет можно, к примеру, вот отсюда;
  2. Переустановите саму проблемную программу (или удалите проблемное обновление, если ошибка начала появляться после такового);
  3. Напишите письмо в техническую поддержку программы (или ресурса) с подробным описанием проблемы и ждите ответа, возможно, разработчики скоро пофиксят баг.
  4. Также, в случае проблем в работе игры Майнкрафт, некоторым пользователям помогло создание новой учётной записи с административными правами, и запуск игры от её имени.Картинка Minecraft

Для разработчиков

Разработчикам стоит обратить внимание на следующее:

  1. Вызывайте методы equals(), а также equalsIgnoreCase() в известной строке литерала, и избегайте вызова данных методов у неизвестного объекта;
  2. Вместо toString() используйте valueOf() в ситуации, когда результат равнозначен;
  3. Применяйте null-безопасные библиотеки и методы;
  4. Старайтесь избегать возвращения null из метода, лучше возвращайте пустую коллекцию;
  5. Применяйте аннотации @Nullable и @NotNull;
  6. Не нужно лишней автоупаковки и автораспаковки в создаваемом вами коде, что приводит к созданию ненужных временных объектов;
  7. Регламентируйте границы на уровне СУБД;
  8. Правильно объявляйте соглашения о кодировании и выполняйте их.Картинка об ошибке java.lang.nullpointerexception

Заключение

При устранении ошибки java.lang.nullpointerexception важно понимать, что данная проблема имеет программную основу, и мало коррелирует с ошибками ПК у обычного пользователя. В большинстве случаев необходимо непосредственное вмешательство разработчиков, способное исправить возникшую проблему и наладить работу программного продукта (или ресурса, на котором запущен сам продукт). В случае же, если ошибка возникла у обычного пользователя (довольно часто касается сбоев в работе игры Minecraft), рекомендуется установить свежий пакет Java на ПК, а также переустановить проблемную программу.

Опубликовано 21.02.2017 Обновлено 03.09.2022

The java.lang.NullPointerException is a runtime exception in Java that occurs when a variable is accessed which is not pointing to any object and refers to nothing or null.

Since the NullPointerException is a runtime exception, it doesn’t need to be caught and handled explicitly in application code.

Why NullPointerException Occurs in Java

The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

Some of the most common scenarios for a NullPointerException are:

  • Calling methods on a null object
  • Accessing a null object’s properties
  • Accessing an index element (like in an array) of a null object
  • Passing null parameters to a method
  • Incorrect configuration for dependency injection frameworks like Spring
  • Using synchronized on a null object
  • Throwing null from a method that throws an exception

NullPointerException Example

Here is an example of a NullPointerException thrown when the length() method of a null String object is called:

public class NullPointerExceptionExample {
    private static void printLength(String str) {
        System.out.println(str.length());
    }

    public static void main(String args[]) {
        String myString = null;
        printLength(myString);
    }
}

In this example, the printLength() method calls the length() method of a String without performing a null check prior to calling the method. Since the value of the string passed from the main() method is null, running the above code causes a NullPointerException:

Exception in thread "main" java.lang.NullPointerException
    at NullPointerExceptionExample.printLength(NullPointerExceptionExample.java:3)
    at NullPointerExceptionExample.main(NullPointerExceptionExample.java:8)

How to Fix NullPointerException

To fix the NullPointerException in the above example, the string should be checked for null or empty 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);
    }
}

The code is updated with a check in the printLength() method that makes sure the string is not empty using the apache commons StringUtils.isNotEmpty() method. Only if the string is not empty the length() method of the string is called, else it prints the message Empty string to console.

How to Avoid NullPointerException

The NullPointerException can be avoided using checks and preventive techniques like the following:

  1. Making sure an object is initialized properly by adding a null check before referencing its methods or properties.
  2. Using Apache Commons StringUtils for String operations e.g. using StringUtils.isNotEmpty() for verifying if a string is empty before using it further.
  3. Using primitives rather than objects where possible, since they cannot have null references e.g. using int instead of Integer and boolean instead of Boolean.

Track, Analyze and Manage Java Errors With Rollbar

Java Error Monitoring with Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates Java error monitoring and triaging, making fixing errors easier than ever. Try it today!

The java.lang.NullPointerException occurs when a java variable does not point to any object and is accessed for any operation. The java.lang.NullPointerException is a runtime exception. The java.lang.NullPointerException is an exception to runtime. The java NullPointerException occurs when a variable is declared but is not assigned to an object until you try to use the variable. You’re referring to something that doesn’t exist.

Null represents a special value in Java. It is primarily used to mean that a reference variable is not assigned to a value or no value. In order to avoid NullPointerException, we must make sure that all objects are correctly initialised before the variable is used. Here we will see How to handle Null Pointer Exception in Java, Best way to avoid Null Pointer Exception in Java.

Exception

Identifying the NullPointerException is quite simple. The NullPointerException print stack trace will display the exception class name and line number. Then look at the code to see what could be null that causes the NullPointerException.

Exception in thread "main" java.lang.NullPointerException
	at com.yawintutor.TestNullPointerException.main(TestNullPointerException.java:8)

Root Cause

The java.lang.NullPointerException occurs in the program when you perform a java variable operation that is assigned to null. There are some common reasons to throw java.lang.NullPointerException in Java program.

Calling the instance method of a null object.
Accessing or modifying the field of a null object.
Taking the length of null as if it were an array.
Accessing or modifying the slots of null as if it were an array.
Throwing null as if it were a Throwable value.

How to reproduce java.lang.NullPointerException

If a java variable is created that does not point to an object and is used to perform some operation, the NullPointerException will be thrown. The example below tries to find the length of the string assigned to null.

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String str = null;
		int length = 0;
		
		length = str.length();

		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Output

Exception in thread "main" java.lang.NullPointerException
	at com.yawintutor.TestNullPointerException.main(TestNullPointerException.java:8)

Solution 1

Identify the java variable that throws java.lang.NullPointerException in the program, make sure the variable is assigned to a value or object. If a value is assigned to the java variable, the java.lang.NullPointerException will be discarded.

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String str = "Yawin";
		int length = 0;
		
		length = str.length();

		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Output

Given String  : Yawin
String Length : 5

Solution 2

If a java.lang.NullPointerException is thrown into a variable, use the ternary operator to set the default value before calling the java variable to perform the operation. If the variable contains a value, the value will be used. Otherwise, the default value would be used to prevent java.lang.NullPointerException.

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String str = null;
		int length = 0;
		
		str = str==null?"":str;
		length = str.length();

		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Output

Given String  : 
String Length : 0

Solution 3

If the java variable throws java.lang.NullPointerException in the program, do a null check before using the variable. If the variable is null, take the alternate path. This will discard the java.lang.NullPointerException.

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String str = null;
		int length = 0;
		
		if(str==null) {
			length = 0;
		} else {
			length = str.length();
		}
		
		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Output

Given String  : null
String Length : 0

Solution 4

If you’re not sure which variable is throwing java.lang.NullPointerException or if there’s a risk of throwing java.lang. NullPointerException at multiple locations, it’s tedious to add null check to the code. Then add a catch block attempt to tackle the java.lang.nullPointerException.

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String str = null;
		int length = 0;
		
		try {
			length = str.length();
		} catch (NullPointerException e) {
			length = 0;
		}

		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Output

Given String  : null
String Length : 0

Solution 5

If you try to find the length of the array assigned to null, the java.lang.nullPointerException will be thrown. If an empty array is assigned to an array variable, the exception will be resolved.

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String[] str = null;
		int length = 0;
		
		length = str.length;

		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Solution

package com.yawintutor;

public class TestNullPointerException {
	public static void main(String[] args) {
		String[] str = new String[0];
		int length = 0;
		
		length = str.length;

		System.out.println("Given String  : " + str);
		System.out.println("String Length : " + length);
	}
}

Output

Given String  : [Ljava.lang.String;@7852e922
String Length : 0

Java NullPointerException (NPE) is an unchecked exception and extends RuntimeException. NullPointerException doesn’t force us to use a try-catch block to handle it.

NullPointerException has been very much a nightmare for most Java developers. It usually pop up when we least expect them.

I have also spent a lot of time while looking for reasons and the best approaches to handle null issues. I will be writing here some of the best practices followed industry-wise, sharing some expert talks and my own learning over time.

  1. 1. Why NullPointerException Occur in the Code?
  2. 2. Common Places Where NPEs Occur?
  3. 3. Best Ways to Avoid NullPointerException
    • 3.1. Use Ternary Operator
    • 3.2. Use Apache Commons StringUtils for String Operations
    • 3.3. Fail Fast Method Arguments
    • 3.4. Consider Primitives instead of Objects
    • 3.5. Carefully Consider Chained Method Calls
    • 3.6. Use valueOf() in place of toString()
    • 3.7. Avoid Returning null from Methods
    • 3.8. Discourage Passing of null as Method Arguments
    • 3.9. Call equals() on ‘Safe’ Non-null Stringd
  4. 4. NullPointerException Safe Operations
    • 4.1. instanceof Operator
    • 4.2. Accessing static Members of a Class
  5. 5. What if we must allow NullPointerException in Some Places

1. Why NullPointerException Occur in the Code?

NullPointerException is a runtime condition where we try to access or modify an object which has not been initialized yet. It essentially means that the object’s reference variable is not pointing anywhere and refers to nothing or ‘null’.

In the given example, String s has been declared but not initialized. When we try to access it in the next statement s.toString(), we get the NullPointerException.

package com.howtodoinjava.demo.npe;

public class SampleNPE
{
   public static void main(String[] args)
   {
      String s = null;
      System.out.println( s.toString() );   // 's' is un-initialized and is null
   }
}

2. Common Places Where NPEs Occur?

Well, NullPointerException can occur anywhere in the code for various reasons but I have prepared a list of the most frequent places based on my experience.

  1. Invoking methods on an object which is not initialized
  2. Parameters passed in a method are null
  3. Calling toString() method on object which is null
  4. Comparing object properties in if block without checking null equality
  5. Incorrect configuration for frameworks like Spring which works on dependency injection
  6. Using synchronized on an object which is null
  7. Chained statements i.e. multiple method calls in a single statement

This is not an exhaustive list. There are several other places and reasons also. If you can recall any such other, please leave a comment. it will help others also.

3. Best Ways to Avoid NullPointerException

3.1. Use Ternary Operator

Ternary operator results in the value on the left-hand side if not null else right-hand side is evaluated. It has syntax like :

boolean expression ? value1 : value2;

If the expression is evaluated as true then the entire expression returns value1 otherwise value2.

It is more like an if-else construct but it is more effective and expressive. To prevent NullPointerException (NPE), use this operator like the below code:

String str = (param == null) ? "NA" : param;

3.2. Use Apache Commons StringUtils for String Operations

Apache Commons Lang is a collection of several utility classes for various kinds of operation. One of them is StringUtils.java.

Use the following methods for better handling the strings in your code.

  • StringUtils.isNotEmpty()
  • StringUtils. IsEmpty()
  • StringUtils.equals()
if (StringUtils.isNotEmpty(obj.getvalue())){
    String s = obj.getvalue();
    ....
}

3.3. Fail Fast Method Arguments

We should always do the method input validation at the beginning of the method so that the rest of the code does not have to deal with the possibility of incorrect input.

Therefore if someone passes in a null as the method argument, things will break early in the execution lifecycle rather than in some deeper location where the root problem will be rather difficult to identify.

Aiming for fail-fast behavior is a good choice in most situations.

3.4. Consider Primitives instead of Objects

A null problem occurs where object references point to nothing. So it is always safe to use primitives. Consider using primitives as necessary because they do not suffer from null references.

All primitives have some default value assigned to them so be careful.

3.5. Carefully Consider Chained Method Calls

While chained statements are nice to look at in the code, they are not NPE friendly.

A single statement spread over several lines will give you the line number of the first line in the stack trace regardless of where it occurs.

ref.method1().method2().method3().methods4();

These kind of chained statement will print only “NullPointerException occurred in line number xyz”. It really is hard to debug such code. Avoid such calls if possible.

3.6. Use valueOf() in place of toString()

If we have to print the string representation of any object, then consider not using toString() method. This is a very soft target for NPE.

Instead use String.valueOf(object). Even if the object is null in this case, it will not give an exception and will print ‘null‘ to the output stream.

3.7. Avoid Returning null from Methods

An awesome tip to avoid NPE is to return empty strings or empty collections rather than null. Java 8 Optionals are a great alternative here.

Do this consistently across your application. You will note that a bucket load of null checks becomes unneeded if you do so.

List<string> data = null;
 
@SuppressWarnings("unchecked")
public List getDataDemo()
{
   if(data == null)
      return Collections.EMPTY_LIST; //Returns unmodifiable list
   return data;
}

Users of the above method, even if they missed the null check, will not see the ugly NPE.

3.8. Discourage Passing of null as Method Arguments

I have seen some method declarations where the method expects two or more parameters. If one parameter is passed as null, then also method works in a different manner. Avoid this.

Instead, we should define two methods; one with a single parameter and the second with two parameters.

Make parameters passing mandatory. This helps a lot when writing application logic inside methods because you are sure that method parameters will not be null; so you don’t put unnecessary assumptions and assertions.

3.9. Call equals() on ‘Safe’ Non-null Stringd

Instead of writing the below code for string comparison

if (param.equals("check me")) {
 // some code
}

write the above code like given below example. This will not cause in NPE even if param is passed as null.

if ("check me".equals(param)) {
 // some code
}

4. NullPointerException Safe Operations

4.1. instanceof Operator

The instanceof operator is NPE safe. So, instanceof null always returns false.

This operator does not cause a NullPointerException. You can eliminate messy conditional code if you remember this fact.

// Unnecessary code
if (data != null &amp;&amp; data instanceof InterestingData) {
}
 
// Less code. Better!!
if (data instanceof InterestingData) {
}

4.2. Accessing static Members of a Class

If you are dealing with static variables or static methods then you won’t get a null pointer exception even if you have your reference variable pointing to null because static variables and method calls are bonded during compile time based on the class name and not associated with the object.

MyObject obj = null;
String attrib = obj.staticAttribute; 

//no NullPointerException because staticAttribute is static variable defined in class MyObject

Please let me know if you know some more such language constructs which do not fail when null is encountered.

5. What if we must allow NullPointerException in Some Places

Joshua bloch in effective java says that “Arguably, all erroneous method invocations boil down to an illegal argument or illegal state, but other exceptions are standardly used for certain kinds of illegal arguments and states. If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.”

So if you must allow NullPointerException in some places in your code then make sure you make them more informative than they usually are.

Take a look at the below example:

package com.howtodoinjava.demo.npe;
 
public class SampleNPE {
   public static void main(String[] args) {
      // call one method at a time
      doSomething(null);
      doSomethingElse(null);
   }
 
   private static String doSomething(final String param) {
      System.out.println(param.toString());
      return "I am done !!";
   }
 
   private static String doSomethingElse(final String param) {
      if (param == null) {
         throw new NullPointerException(
               " :: Parameter 'param' was null inside method 'doSomething'.");
      }
      System.out.println(param.toString());
      return "I am done !!";
   }
}

Output of both method calls is this:

Exception in thread "main" java.lang.NullPointerException
 at com.howtodoinjava.demo.npe.SampleNPE.doSomething(SampleNPE.java:14)
 at com.howtodoinjava.demo.npe.SampleNPE.main(SampleNPE.java:8)
 
Exception in thread "main" java.lang.NullPointerException:  :: Parameter 'param' was null inside method 'doSomething'.
 at com.howtodoinjava.demo.npe.SampleNPE.doSomethingElse(SampleNPE.java:21)
 at com.howtodoinjava.demo.npe.SampleNPE.main(SampleNPE.java:8)

Clearly, the second stack trace is more informative and makes debugging easy. Use this in the future.

I am done with my experience around NullPointerException. If you know other points around the topic, please share with all of us !!

Happy Learning !!

Понравилась статья? Поделить с друзьями:
  • Как исправить ошибку internal exception io netty handler codec decoderexception
  • Как исправить ошибку installation has failed при попытке установить faceit
  • Как исправить ошибку installation has failed при попытке установить discord на windows 10
  • Как исправить ошибку install windows
  • Как исправить ошибку input not supported на виндовс 10