Ошибка null pointer conversion

Время на прочтение
5 мин

Количество просмотров 270K

Эта простая статья скорее для начинающих разработчиков Java, хотя я нередко вижу и опытных коллег, которые беспомощно глядят на stack trace, сообщающий о NullPointerException (сокращённо NPE), и не могут сделать никаких выводов без отладчика. Разумеется, до NPE своё приложение лучше не доводить: вам помогут null-аннотации, валидация входных параметров и другие способы. Но когда пациент уже болен, надо его лечить, а не капать на мозги, что он ходил зимой без шапки.

Итак, вы узнали, что ваше приложение упало с NPE, и у вас есть только stack trace. Возможно, вам прислал его клиент, или вы сами увидели его в логах. Давайте посмотрим, какие выводы из него можно сделать.

NPE может произойти в трёх случаях:

  1. Его кинули с помощью throw
  2. Кто-то кинул null с помощью throw
  3. Кто-то пытается обратиться по null-ссылке

Во втором и третьем случае message в объекте исключения всегда null, в первом может быть произвольным. К примеру, java.lang.System.setProperty кидает NPE с сообщением «key can’t be null», если вы передали в качестве key null. Если вы каждый входной параметр своих методов проверяете таким же образом и кидаете исключение с понятным сообщением, то вам остаток этой статьи не потребуется.

Обращение по null-ссылке может произойти в следующих случаях:

  1. Вызов нестатического метода класса
  2. Обращение (чтение или запись) к нестатическому полю
  3. Обращение (чтение или запись) к элементу массива
  4. Чтение length у массива
  5. Неявный вызов метода valueOf при анбоксинге (unboxing)

Важно понимать, что эти случаи должны произойти именно в той строчке, на которой заканчивается stack trace, а не где-либо ещё.

Рассмотрим такой код:

 1: class Data {
 2:    private String val;
 3:    public Data(String val) {this.val = val;}
 4:    public String getValue() {return val;}
 5: }
 6:
 7: class Formatter {
 8:    public static String format(String value) {
 9:        return value.trim();
10:    }
11: }
12:
13: public class TestNPE {
14:    public static String handle(Formatter f, Data d) {
15:        return f.format(d.getValue());
16:    }
17: }

Откуда-то был вызван метод handle с какими-то параметрами, и вы получили:

Exception in thread "main" java.lang.NullPointerException
    at TestNPE.handle(TestNPE.java:15)

В чём причина исключения — в f, d или d.val? Нетрудно заметить, что f в этой строке вообще не читается, так как метод format статический. Конечно, обращаться к статическому методу через экземпляр класса плохо, но такой код встречается (мог, например, появиться после рефакторинга). Так или иначе значение f не может быть причиной исключения. Если бы d был не null, а d.val — null, тогда бы исключение возникло уже внутри метода format (в девятой строчке). Аналогично проблема не могла быть внутри метода getValue, даже если бы он был сложнее. Раз исключение в пятнадцатой строчке, остаётся одна возможная причина: null в параметре d.

Вот другой пример:

 1: class Formatter {
 2:     public String format(String value) {
 3:         return "["+value+"]";
 4:     }
 5: }
 6: 
 7: public class TestNPE {
 8:     public static String handle(Formatter f, String s) {
 9:         if(s.isEmpty()) {
10:             return "(none)";
11:         }
12:         return f.format(s.trim());
13:     }
14: }

Снова вызываем метод handle и получаем

Exception in thread "main" java.lang.NullPointerException
	at TestNPE.handle(TestNPE.java:12)

Теперь метод format нестатический, и f вполне может быть источником ошибки. Зато s не может быть ни под каким соусом: в девятой строке уже было обращение к s. Если бы s было null, исключение бы случилось в девятой строке. Просмотр логики кода перед исключением довольно часто помогает отбросить некоторые варианты.

С логикой, конечно, надо быть внимательным. Предположим, условие в девятой строчке было бы написано так:

if("".equals(s))

Теперь в самой строчке обращения к полям и методам s нету, а метод equals корректно обрабатывает null, возвращая false, поэтому в таком случае ошибку в двенадцатой строке мог вызвать как f, так и s. Анализируя вышестоящий код, уточняйте в документации или исходниках, как используемые методы и конструкции реагируют на null. Оператор конкатенации строк +, к примеру, никогда не вызывает NPE.

Вот такой код (здесь может играть роль версия Java, я использую Oracle JDK 1.7.0.45):

 1: import java.io.PrintWriter;
 2: 
 3: public class TestNPE {
 4:     public static void dump(PrintWriter pw, MyObject obj) {
 5:         pw.print(obj);
 6:     }
 7: }

Вызываем метод dump, получаем такое исключение:

Exception in thread "main" java.lang.NullPointerException
	at java.io.PrintWriter.write(PrintWriter.java:473)
	at java.io.PrintWriter.print(PrintWriter.java:617)
	at TestNPE.dump(TestNPE.java:5)

В параметре pw не может быть null, иначе нам не удалось бы войти в метод print. Возможно, null в obj? Легко проверить, что pw.print(null) выводит строку «null» без всяких исключений. Пойдём с конца. Исключение случилось здесь:

472: public void write(String s) {
473:     write(s, 0, s.length());
474: }

В строке 473 возможна только одна причина NPE: обращение к методу length строки s. Значит, s содержит null. Как так могло получиться? Поднимемся по стеку выше:

616: public void print(Object obj) {
617:     write(String.valueOf(obj));
618: }

В метод write передаётся результат вызова метода String.valueOf. В каком случае он может вернуть null?

public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}

Единственный возможный вариант — obj не null, но obj.toString() вернул null. Значит, ошибку надо искать в переопределённом методе toString() нашего объекта MyObject. Заметьте, в stack trace MyObject вообще не фигурировал, но проблема именно там. Такой несложный анализ может сэкономить кучу времени на попытки воспроизвести ситуацию в отладчике.

Не стоит забывать и про коварный автобоксинг. Пусть у нас такой код:

 1: public class TestNPE {
 2:     public static int getCount(MyContainer obj) {
 3:         return obj.getCount();
 4:     }
 5: }

И такое исключение:

Exception in thread "main" java.lang.NullPointerException
	at TestNPE.getCount(TestNPE.java:3)

На первый взгляд единственный вариант — это null в параметре obj. Но следует взглянуть на класс MyContainer:

import java.util.List;

public class MyContainer {
    List<String> elements;
    
    public MyContainer(List<String> elements) {
        this.elements = elements;
    }
    
    public Integer getCount() {
        return elements == null ? null : elements.size();
    }
}

Мы видим, что getCount() возвращает Integer, который автоматически превращается в int именно в третьей строке TestNPE.java, а значит, если getCount() вернул null, произойдёт именно такое исключение, которое мы видим. Обнаружив класс, подобный классу MyContainer, посмотрите в истории системы контроля версий, кто его автор, и насыпьте ему крошек под одеяло.

Помните, что если метод принимает параметр int, а вы передаёте Integer null, то анбоксинг случится до вызова метода, поэтому NPE будет указывать на строку с вызовом.

В заключение хочется пожелать пореже запускать отладчик: после некоторой тренировки анализ кода в голове нередко выполняется быстрее, чем воспроизведение трудноуловимой ситуации.

Эта простая статья скорее для начинающих разработчиков Java, хотя я нередко вижу и опытных коллег, которые беспомощно глядят на stack trace, сообщающий о NullPointerException (сокращённо NPE), и не могут сделать никаких выводов без отладчика. Разумеется, до NPE своё приложение лучше не доводить: вам помогут null-аннотации, валидация входных параметров и другие способы. Но когда пациент уже болен, надо его лечить, а не капать на мозги, что он ходил зимой без шапки.

Итак, вы узнали, что ваше приложение упало с NPE, и у вас есть только stack trace. Возможно, вам прислал его клиент, или вы сами увидели его в логах. Давайте посмотрим, какие выводы из него можно сделать.

NPE может произойти в трёх случаях:

  1. Его кинули с помощью throw
  2. Кто-то кинул null с помощью throw
  3. Кто-то пытается обратиться по null-ссылке

Во втором и третьем случае message в объекте исключения всегда null, в первом может быть произвольным. К примеру, java.lang.System.setProperty кидает NPE с сообщением «key can’t be null», если вы передали в качестве key null. Если вы каждый входной параметр своих методов проверяете таким же образом и кидаете исключение с понятным сообщением, то вам остаток этой статьи не потребуется.

Обращение по null-ссылке может произойти в следующих случаях:

  1. Вызов нестатического метода класса
  2. Обращение (чтение или запись) к нестатическому полю
  3. Обращение (чтение или запись) к элементу массива
  4. Чтение length у массива
  5. Неявный вызов метода valueOf при анбоксинге (unboxing)

Важно понимать, что эти случаи должны произойти именно в той строчке, на которой заканчивается stack trace, а не где-либо ещё.

Рассмотрим такой код:

 1: class Data {
 2:    private String val;
 3:    public Data(String val) {this.val = val;}
 4:    public String getValue() {return val;}
 5: }
 6:
 7: class Formatter {
 8:    public static String format(String value) {
 9:        return value.trim();
10:    }
11: }
12:
13: public class TestNPE {
14:    public static String handle(Formatter f, Data d) {
15:        return f.format(d.getValue());
16:    }
17: }

Откуда-то был вызван метод handle с какими-то параметрами, и вы получили:

Exception in thread "main" java.lang.NullPointerException
    at TestNPE.handle(TestNPE.java:15)

В чём причина исключения — в f, d или d.val? Нетрудно заметить, что f в этой строке вообще не читается, так как метод format статический. Конечно, обращаться к статическому методу через экземпляр класса плохо, но такой код встречается (мог, например, появиться после рефакторинга). Так или иначе значение f не может быть причиной исключения. Если бы d был не null, а d.val — null, тогда бы исключение возникло уже внутри метода format (в девятой строчке). Аналогично проблема не могла быть внутри метода getValue, даже если бы он был сложнее. Раз исключение в пятнадцатой строчке, остаётся одна возможная причина: null в параметре d.

Вот другой пример:

 1: class Formatter {
 2:     public String format(String value) {
 3:         return "["+value+"]";
 4:     }
 5: }
 6: 
 7: public class TestNPE {
 8:     public static String handle(Formatter f, String s) {
 9:         if(s.isEmpty()) {
10:             return "(none)";
11:         }
12:         return f.format(s.trim());
13:     }
14: }

Снова вызываем метод handle и получаем

Exception in thread "main" java.lang.NullPointerException
	at TestNPE.handle(TestNPE.java:12)

Теперь метод format нестатический, и f вполне может быть источником ошибки. Зато s не может быть ни под каким соусом: в девятой строке уже было обращение к s. Если бы s было null, исключение бы случилось в девятой строке. Просмотр логики кода перед исключением довольно часто помогает отбросить некоторые варианты.

С логикой, конечно, надо быть внимательным. Предположим, условие в девятой строчке было бы написано так:

if("".equals(s))

Теперь в самой строчке обращения к полям и методам s нету, а метод equals корректно обрабатывает null, возвращая false, поэтому в таком случае ошибку в двенадцатой строке мог вызвать как f, так и s. Анализируя вышестоящий код, уточняйте в документации или исходниках, как используемые методы и конструкции реагируют на null. Оператор конкатенации строк +, к примеру, никогда не вызывает NPE.

Вот такой код (здесь может играть роль версия Java, я использую Oracle JDK 1.7.0.45):

 1: import java.io.PrintWriter;
 2: 
 3: public class TestNPE {
 4:     public static void dump(PrintWriter pw, MyObject obj) {
 5:         pw.print(obj);
 6:     }
 7: }

Вызываем метод dump, получаем такое исключение:

Exception in thread "main" java.lang.NullPointerException
	at java.io.PrintWriter.write(PrintWriter.java:473)
	at java.io.PrintWriter.print(PrintWriter.java:617)
	at TestNPE.dump(TestNPE.java:5)

В параметре pw не может быть null, иначе нам не удалось бы войти в метод print. Возможно, null в obj? Легко проверить, что pw.print(null) выводит строку «null» без всяких исключений. Пойдём с конца. Исключение случилось здесь:

472: public void write(String s) {
473:     write(s, 0, s.length());
474: }

В строке 473 возможна только одна причина NPE: обращение к методу length строки s. Значит, s содержит null. Как так могло получиться? Поднимемся по стеку выше:

616: public void print(Object obj) {
617:     write(String.valueOf(obj));
618: }

В метод write передаётся результат вызова метода String.valueOf. В каком случае он может вернуть null?

public static String valueOf(Object obj) {
   return (obj == null) ? "null" : obj.toString();
}

Единственный возможный вариант — obj не null, но obj.toString() вернул null. Значит, ошибку надо искать в переопределённом методе toString() нашего объекта MyObject. Заметьте, в stack trace MyObject вообще не фигурировал, но проблема именно там. Такой несложный анализ может сэкономить кучу времени на попытки воспроизвести ситуацию в отладчике.

Не стоит забывать и про коварный автобоксинг. Пусть у нас такой код:

 1: public class TestNPE {
 2:     public static int getCount(MyContainer obj) {
 3:         return obj.getCount();
 4:     }
 5: }

И такое исключение:

Exception in thread "main" java.lang.NullPointerException
	at TestNPE.getCount(TestNPE.java:3)

На первый взгляд единственный вариант — это null в параметре obj. Но следует взглянуть на класс MyContainer:

import java.util.List;

public class MyContainer {
    List<String> elements;
    
    public MyContainer(List<String> elements) {
        this.elements = elements;
    }
    
    public Integer getCount() {
        return elements == null ? null : elements.size();
    }
}

Мы видим, что getCount() возвращает Integer, который автоматически превращается в int именно в третьей строке TestNPE.java, а значит, если getCount() вернул null, произойдёт именно такое исключение, которое мы видим. Обнаружив класс, подобный классу MyContainer, посмотрите в истории системы контроля версий, кто его автор, и насыпьте ему крошек под одеяло.

Помните, что если метод принимает параметр int, а вы передаёте Integer null, то анбоксинг случится до вызова метода, поэтому NPE будет указывать на строку с вызовом.

В заключение хочется пожелать пореже запускать отладчик: после некоторой тренировки анализ кода в голове нередко выполняется быстрее, чем воспроизведение трудноуловимой ситуации.

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 и как эффективно предотвращать такие ситуации при разработке программ.

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

NullPointerException появляется, если программа обращается или получает доступ к объекту, а ссылка на него равна нулю (null).

Это исключение возникает следующих случаях:

  • Вызов метода из объекта значения null.
  • Доступ или изменение объекта поля null.
  • Принимает длину null(если бы это был массив Java).
  • Доступ или изменение ячеек объекта null.
  • Показывает «0», значение Throwable.
  • При попытке синхронизации по нулевому объекту.

NullPointerException является RuntimeException, и, таким образом, компилятор Javac не заставляет вас использовать блок try-catch для соответствующей обработки.

ошибка error java lang nullpointerexception

Как уже упоминалось, null – это специальное значение, используемое в Java. Это чрезвычайно полезно при кодировании некоторых шаблонов проектирования, таких как Null Object pattern и шаблон Singleton pattern.

Шаблон Singleton обеспечивает создание только одного экземпляра класса, а также направлен на предоставление глобального доступа к объекту.

Например, простой способ создания не более одного экземпляра класса – объявить все его конструкторы как частные, а затем создать открытый метод, который возвращает уникальный экземпляр класса:

import java.util.UUID;

class Singleton {

     private static Singleton single = null;
     private String ID = null;

     private Singleton() {
          /* Make it private, in order to prevent the creation of new instances of
           * the Singleton class. */

          ID = UUID.randomUUID().toString(); // Create a random ID.
     }

     public static Singleton getInstance() {
          if (single == null)
               single = new Singleton();

          return single;
     }

     public String getID() {
          return this.ID;
     }
}

public class TestSingleton {
     public static void main(String[] args) {
          Singleton s = Singleton.getInstance();
          System.out.println(s.getID());
     }
}

В этом примере мы объявляем статический экземпляр класса Singleton. Этот экземпляр инициализируется не более одного раза внутри метода getInstance.

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

Как избежать исключения Null Pointer

Чтобы решить и избежать исключения NullPointerException, убедитесь, что все ваши объекты инициализированы должным образом, прежде чем использовать их.

Когда вы объявляете ссылочную переменную, вы должны создать указатель на объект и убедиться, что указатель не является нулевым, прежде чем запрашивать метод или поле у ​​объекта.

Кроме того, если выдается исключение, используйте информацию, находящуюся в трассировке стека исключения. Трассировка стека выполнения обеспечивается JVM, чтобы включить отладку. Найдите метод и строку, в которой было обнаружено исключение, а затем выясните, какая ссылка равна нулю в этой конкретной строке.

Опишем некоторые методы, которые имеют дело с вышеупомянутым исключением. Однако они не устраняют проблему, и программист всегда должен быть осторожен.

  1. Сравнение строк с литералами

Очень распространенный случай, выполнения программы включает сравнение между строковой переменной и литералом. Литерал может быть строкой или элементом Enum.

Вместо того, чтобы вызывать метод из нулевого объекта, рассмотрите возможность вызова его из литерала. Например:

String str = null;
if(str.equals("Test")) {
     /* The code here will not be reached, as an exception will be thrown. */
}

Приведенный выше фрагмент кода вызовет исключение NullPointerException. Однако, если мы вызываем метод из литерала, поток выполнения продолжается нормально:

String str = null;
if("Test".equals(str)) {
     /* Correct use case. No exception will be thrown. */
}
  1. Проверка аргументов метода

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

В противном случае вы можете вызвать исключение IllegalArgumentException.

Например:

public static int getLength(String s) {
     if (s == null)
          throw new IllegalArgumentException("The argument cannot be null");

     return s.length();
}
  1. Предпочтение метода String.valueOf() вместо of toString()

Когда код вашей программы требует строковое представление объекта, избегайте использования метода toString объекта. Если ссылка вашего объекта равна нулю, генерируется исключение NullPointerException.

Вместо этого рассмотрите возможность использования статического метода String.valueOf, который не выдает никаких исключений и «ноль», если аргумент функции равен нулю.

  1. Используйте Ternary Operator

Ternary Operator – может быть очень полезным. Оператор имеет вид:

boolean expression ? value1 : value2;

Сначала вычисляется логическое выражение. Если выражение true, то возвращается значение1, в противном случае возвращается значение2. Мы можем использовать Ternary Operator для обработки нулевых указателей следующим образом:

String message = (str == null) ? "" : str.substring(0, 10);

Переменная message будет пустой, если ссылка str равна нулю. В противном случае, если str указывает на фактические данные, в сообщении будут первые 10 символов.

  1. создайте методы, которые возвращают пустые коллекции вместо нуля.

Очень хорошая техника – создавать методы, которые возвращают пустую коллекцию вместо нулевого значения. Код вашего приложения может перебирать пустую коллекцию и использовать ее методы и поля. Например:

public class Example {
     private static List<Integer> numbers = null;

     public static List<Integer> getList() {
          if (numbers == null)
               return Collections.emptyList();
          else
               return numbers;
     }
}
  1. Воспользуйтесь классом Apache’s StringUtils.

Apache’s Commons Lang – это библиотека, которая предоставляет вспомогательные утилиты для API java.lang, такие как методы манипулирования строками.

Примером класса, который обеспечивает манипулирование String, является StringUtils.java, который спокойно обрабатывает входные строки с нулевым значением.

Вы можете воспользоваться методами: StringUtils.isNotEmpty, StringUtils.IsEmpty и StringUtils.equalsчтобы избежать NullPointerException. Например:

if (StringUtils.isNotEmpty(str)) {
     System.out.println(str.toString());
}
  1. Используйте методы: contains(), containsKey(), containsValue()

Если в коде вашего приложения используется Maps, рассмотрите возможность использования методов contains, containsKey и containsValue. Например, получить значение определенного ключа после того, как вы проверили его существование на карте:

Map<String, String> map = …
…
String key = …
String value = map.get(key);
System.out.println(value.toString()); // An exception will be thrown, if the value is null.

System.out.println(value.toString()); // В приведенном выше фрагменте мы не проверяем, существует ли на самом деле ключ внутри карты, и поэтому возвращаемое значение может быть нулевым. Самый безопасный способ следующий:

Map<String, String> map = …
…
String key = …
if(map.containsKey(key)) {
     String value = map.get(key);
     System.out.println(value.toString()); // No exception will be thrown.
}
  1. Проверьте возвращаемое значение внешних методов

На практике очень часто используются внешние библиотеки. Эти библиотеки содержат методы, которые возвращают ссылку. Убедитесь, что возвращаемая ссылка не пуста.

  1. Используйте Утверждения

Утверждения очень полезны при тестировании вашего кода и могут использоваться, чтобы избежать выполнения фрагментов кода. Утверждения Java реализуются с помощью ключевого слова assert и выдают AssertionError.

Обратите внимание, что вы должны включить флажок подтверждения JVM, выполнив его с аргументом -ea. В противном случае утверждения будут полностью проигнорированы.

Примером использования утверждений Java является такая версия кода:

public static int getLength(String s) {
     /* Ensure that the String is not null. */
     assert (s != null);

     return s.length();
}

Если вы выполните приведенный выше фрагмент кода и передадите пустой аргумент getLength, появится следующее сообщение об ошибке:
Exception in thread "main" java.lang.AssertionError
Также вы можете использовать класс Assert предоставленный средой тестирования jUnit.

  1. Модульные тесты

Модульные тесты могут быть чрезвычайно полезны при тестировании функциональности и правильности вашего кода. Уделите некоторое время написанию пары тестовых примеров, которые подтверждают, что исключение NullPointerException не возникает.

Существующие безопасные методы NullPointerException

Доступ к статическим членам или методам класса

Когда ваш вы пытаетесь получить доступ к статической переменной или методу класса, даже если ссылка на объект равна нулю, JVM не выдает исключение.

Это связано с тем, что компилятор Java хранит статические методы и поля в специальном месте во время процедуры компиляции. Статические поля и методы связаны не с объектами, а с именем класса.

class SampleClass {

     public static void printMessage() {
          System.out.println("Hello from Java Code Geeks!");
     }
}

public class TestStatic {
     public static void main(String[] args) {
          SampleClass sc = null;
          sc.printMessage();
     }
}

Несмотря на тот факт, что экземпляр SampleClass равен нулю, метод будет выполнен правильно. Однако, когда речь идет о статических методах или полях, лучше обращаться к ним статическим способом, например, SampleClass.printMessage ().

Оператор instanceof

Оператор instanceof может использоваться, даже если ссылка на объект равна нулю.

Оператор instanceof возвращает false, когда ссылка равна нулю.

String str = null;
if(str instanceof String)
     System.out.println("It's an instance of the String class!");
else
     System.out.println("Not an instance of the String class!");

В результате, как и ожидалось:

Not an instance of the String class!

Смотрите видео, чтобы стало понятнее.

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 !!

  1. Что такое NullPointerException в Java?
  2. Обработка класса NullPointerException в Java
  3. Обработка класса NullPointerException в Java
  4. Встречи с NullPointerException в аргументах командной строки в Java

Что такое исключение нулевого указателя в Java

В этом руководстве рассказывается об исключении нулевого указателя Java и о том, как с ним справиться. Мы включили несколько примеров программ, которым вы можете следовать.

В Java значение по умолчанию для любой ссылочной переменной — это нулевое значение, указывающее на ячейку памяти, но не имеющее связанного значения. Когда программист пытается выполнить какую-либо операцию с этой ссылочной переменной, он генерирует исключение нулевого указателя из-за нулевых условий.

Это сценарий, в котором может возникнуть это исключение, но это исключение чаще всего встречается в Java, что нарушает код и приводит к ненормальным потокам выполнения. Следующие пункты могут вызвать NullPointerException в Java-коде:

  • Вызов метода экземпляра нулевого объекта.
  • Изменение поля нулевого объекта.
  • Обработка длины нуля, как если бы это был массив.

Для обработки этого исключения Java предоставляет класс NullPointerException, расположенный в пакете java.lang. Мы можем использовать этот класс в блоке catch, чтобы указать тип исключения, а затем перехватить его, чтобы избежать нарушения кода.

Что такое NullPointerException в Java?

Самый простой пример для понимания класса NullPointerException — это создание string объекта, а затем применение такого метода, как toUpperCase(), для преобразования строки в верхний регистр. Посмотрите на пример ниже и обратите внимание, что он вызывает исключение, потому что объект string пуст:

public class SimpleTesting{
    static String str;
    public static void main(String[] args) {
        String newStr = str.toUpperCase();
        System.out.println(newStr);
    }
}

Выход:

Exception in thread "main" java.lang.NullPointerException

Обработка класса NullPointerException в Java

Для обработки исключений Java предоставляет блок try-catch. Здесь мы можем использовать эти блоки, чтобы поймать NullPointerException и избежать аварийного завершения программы. Посмотрите пример ниже:

public class SimpleTesting{
    static String str;
    public static void main(String[] args) {
        try {
            String newStr = str.toUpperCase();
            System.out.println(newStr);
        }catch(NullPointerException e) {
            System.out.println("Null Pointer: "+e.getMessage());
        }
    }
}

Выход:

Обработка класса NullPointerException в Java

Если вы уже знаете о пустой ссылке, вы можете использовать блок if-else для проверки переменной перед применением любой операции. Этот метод — отличное решение, но он работает только в том случае, если вы заранее знаете нулевую ссылку. Смотрите код здесь:

public class SimpleTesting{
    static String str;
     public static void main(String[] args) {
        if(str != null) {
            String newStr = str.toUpperCase();
            System.out.println(newStr);
        }else 
            System.out.println("String is null");
    }
}

Выход:

Встречи с NullPointerException в аргументах командной строки в Java

Это еще один сценарий, при котором может возникнуть исключение нулевого указателя. Массив args[] метода main() содержит аргументы командной строки, и если во время выполнения аргумент не указан, то он указывает на пустую ссылку. Получение его длины вернет NullPointerException. См. Пример ниже:

public class SimpleTesting{
    static String[] arr;
    public static void main(String[] args) {
        int length = arr.length;
        System.out.println("Array length : "+length);
    }
}

Выход:

Exception in thread "main" java.lang.NullPointerException

Когда вы объявляете переменную ссылочного типа, на самом деле вы создаете ссылку на объект данного типа. Рассмотрим следующий код для объявления переменной типа int:

int x;
x = 10;

В этом примере переменная x имеет тип int и Java инициализирует её как 0. Когда вы присвоите переменной значение 10 (вторая строка), это значение сохранится в ячейке памяти, на которую ссылается x.

Но когда вы объявляете ссылочный тип, процесс выглядит иначе. Посмотрим на следующий код:

Integer num;
num = new Integer(10);

В первой строке объявлена переменная num, ее тип не относится к встроенному, следовательно, значением является ссылка (тип этой переменной, Integer, является ссылочным типом). Поскольку вы еще не указали, на что собираетесь ссылаться, Java присвоит переменной значение Null, подразумевая «Я ни на что не ссылаюсь».

Во второй строке, ключевое слово new используется для создания объекта типа Integer. Этот объект имеет адрес в памяти, который присваивается переменной num. Теперь, с помощью переменной num вы можете обратиться к объекту используя оператора разыменования ..

Исключение, о котором вы говорите в вопросе, возникает, если вы объявили переменную, но не создали объект, то есть если вы попытаетесь разыменовать num до того, как создали объект, вы получите NullPointerException. В самом простом случае, компилятор обнаружит проблему и сообщит, что

num may not have been initialized

Что говорит: «возможно, переменная num не инициализирована».

Иногда исключение вызвано именно тем, что объект действительно не был создан. К примеру, у вас может быть следующая функция:

public void doSomething(Integer num){
   // Работаем с num
}

В этом случае создание объекта (переменная num) лежит на вызывающем коде, то есть вы предполагаете, что он был создан ранее – до вызова метода doSomething. К сожалению, следующий вызов метода вполне возможен:

doSomething(null);

В этом случае значение переменной num будет null. Лучшим способом избежать данного исключения будет проверка на равенство нулю. Как результат, функция doSomething должна быть переписана следующим образом:

public void doSomething(Integer num){
    if (num != null) {
       // Работаем с num
    }
}

Как альтернативный вариант предыдущему примеру вы можете сообщить вызывающему коду, что метод был вызван с неверными параметрами, например, с помощью IllegalArgumentException.

public void doSomething(Integer num){
    if (num == null)
        throw new IllegalArgumentException("Num не должен быть null"); 
    // Работаем с num
}

Также, обратите внимание на вопрос «Что такое stack trace и как с его помощью находить ошибки при разработке приложений?».

Перевод ответа «What is a Null Pointer Exception, and how do I fix it?» @Vincent Ramdhanie.

You have just finished creating an Android-based application and attempt to execute it. As far as you know, the application is fine, there are no syntax errors and the code should just work fine. But when you run it now, your application quits saying an uncaught RuntimeException was thrown. Attempting to dig up the cause, you find something that gives you a clue: a NullPointerException has occurred.

With this, you begin your journey into the world of exception handling with Android, in particular, handling NullPointerException. In this post, we’ll discuss how to fix NullPointerExceptions in Android apps.

Jump ahead:

  • What is a NullPointerException?
    • Why do NullPointerExceptions occur?
  • Avoiding NullPointerExceptions in Java
    • Using SmartCast
    • Using the Elvis operator
  • Avoiding NullPointerExceptions in Kotlin
  • Using logcat to detect and fix a NullPointerException in Android Studio
  • Setting breakpoints to debug NullPointerExceptions

What is a NullPointerException?

First, let’s quickly refresh ourselves on exceptions. They are events or abnormal conditions in a program that occur during execution and disrupt the normal flow of the program.

An exception can occur for different reasons, such as:

  • A user enters invalid data to a field
  • A file that must be opened cannot be found
  • A network connection is lost in the middle of communication
  • The JVM has run out of memory

When an error occurs inside a method, it throws an exception. A NullPointerException is one of the most common runtime exceptions.

In Java, null is a special value that represents the absence of a value. When you try to use a null value, you get a NullPointerException because the operation you are trying to perform cannot be completed on a null value.

In Kotlin, null is not a value, but a type of its own called nullable. By default, every object in Kotlin is non-null, which means it cannot have a null value.

Why do NullPointerExceptions occur?

You might encounter a NullPointerException when trying to access a view, resource, or data that hasn’t been properly initialized or loaded yet. Some of the situations in which a NullPointerException can occur in Java, according to the Java Language Specification, include:

  • Attempting to access elements of a null array
  • Using switch with a null expression
  • Accessing instance fields of null references
  • Invoking instance methods of a null reference
  • Using an integer or floating point operator that has one of its operands as a boxed null reference
  • Attempting an unboxing conversion with the boxed value as null
  • Calling super on a null reference

Avoiding NullPointerExceptions in Java

Below are some best practices to avoid NullPointerExceptions in Java:

  • String comparison with literals
  • Avoid returning null from your methods
  • Keep checking arguments of methods
  • Use String.valueOf() rather than toString()
  • Using primitives data types as much as possible
  • Avoid chained method calls
  • Use ternary operator

By contrast, Kotlin is a smarter, more modern language that has been designed to avoid NullPointerExceptions through several mechanisms, such as:

  • Using nullable and non-nullable types
  • Using the SmartCast feature
  • Safe calls
  • The Elvis operator

In Kotlin, all regular types are non-nullable unless you explicitly mark them as nullable with a question mark ?, e.g., String?.

Consider the below Kotlin code:

fun getlen(name: String) = name.length

The parameter name has a type of String, which means it must always contain a String instance and cannot contain null. This code ensures that a NullPointerException at runtime is unlikely to occur.

Instead, any attempt to pass a null value to the getlen(name: String) function will cause a compile-time error: Null cannot be a value of a non-null type String. This is because the compiler has enforced the rule that arguments of getlen() cannot be null.

Consider the below snippet, in which the code is obvious to us but may not be immediately obvious to the compiler:

class TestNPE {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
        var m : String? // here, m is declared as nullable
println("m is : $m")
var x: Int
x = 150
if (x == 150)
    println("Value of m is : $m")
        }
    }
}

The compiler raises a compiler error because m is not initialized:

A compiler error is raised because m is not initialized

Thus, instead of proceeding to runtime and then raising an exception, it stops at the compilation stage with a compiler error.

Using SmartCast

In order to use nullable types, Kotlin has an option called safe cast, or smart cast. Through this feature, the Kotlin compiler will trace situations inside if and other conditional expressions. So, if the compiler finds a variable belonging to a non-null type, it will allow you to access this variable safely.

In certain cases, it is not possible for the compiler to cast types, in which case it will throw an exception; this is called unsafe casting. Consider a nullable string (String?) which cannot be cast to a non-nullable string (String). It will throw an exception.

Kotlin addresses this by providing a safe cast operator as? to cast safely to another type. If casting is not possible, it returns a null rather than throwing a ClassCastException.

Example:

val aInt: Int? = a as? Int

Using the Elvis operator ?:

Kotlin also has an advanced operator called the Elvis operator (?:) that returns either a non-null value or the default value, even if the conditional expression is null. It also checks the null safety of values.

Consider an example:

val count = attendance?.length ?: -1

This means:

val count: Int = if (attendance != null) attendance.length else -1

Despite this, an NullPointerException could still occur in Kotlin-based Android applications.

Consider the earlier example of class TestNPE. Now, the code is modified such that m is initialized but is used with a non-null assertion operator (!!), which converts a given value to a non-null type and throws an exception if the value is null.

class TestNPE {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            var m: String?=null // here, m is declared
//as nullable
            var x: Int
            x = 150
            if (x == 150)
            println("m is : $m")
            var mlen = m!!.length
            println("length of m is : $mlen")
        }
    }
}

In this case, a NullPointerException will be thrown, as shown here:

A NullPointerException is thrown

Avoiding NullPointerExceptions in Kotlin

A few causes of a NullPointerException in Kotlin are:

  • Explicitly calling throw NullPointerException()
  • Using the !! operator
  • Data inconsistency with regard to initialization
  • Java interoperation

To prevent NullPointerExceptions, you should always ensure that your variables and objects are properly initialized before you use them. You can also use null checks or try … catch blocks to handle possible null values and prevent your app from crashing.

An extremely simplified example of using try … catch is given below:

class TestNPE {
    companion object {
        @JvmStatic
        fun main(args: Array<String>) {
            var m: String?=null // here, m is declared 
//as nullable
           try {
               var x: Int
               x = 150
               if (x == 150)
                   println("m is : $m")
               var mlen = m!!.length
               println("length of m is : $mlen")
           }catch( ne: NullPointerException)
           {
               println("Null Pointer Exception has 
occurred. ")
           }
        }
    }
}

The code that is likely to cause a NullPointerException is enclosed in a try … catch block.

The advantage here is that the developer has control over what must be done when the exception is thrown. Here, a simple message is displayed. In practical scenarios, one can close any currently open resources, such as files, before terminating the program.

Using logcat to detect and fix a NullPointerException in Android Studio

Whenever an Android application crashes, a stack trace is written to the console that contains vital information that can help identify and solve the issue. There are two ways to get to this stack trace:

    1. Using Google’s adb shell utility to obtain a logcat file, which can help explain why the application crashed:
      adb logcat > logcat.txt
      

      Open logcat.txt and search for the application name. It will have information on why the application failed along with other details such as line number, class name, and so on

    2. In Android Studio, either press Alt + 6, or click the Logcat button in the status bar. Make sure your emulator or device is selected in the Devices panel, then locate the stack trace.Locate the stack trace in Android Studio

There may be a lot of stuff logged into logcat, so you may need to scroll a bit, or you can clear the logcat through the Recycle Bin option and let the app crash again to bring the most recent stack trace in the log to the top.

An important point of note is that if your app is already live, then you cannot use logcat.

Android Studio Electric Eel’s latest version has an updated logcat, which facilitates easier parsing, querying, and tracking of logs. The new logcat also:

  • Formats logs for easy scanning for tags, messages, and other useful information
  • Identifies various types of logs, such as warnings and errors.
  • Makes it easier to track logs from your app across app crashes and restarts

When logcat notices that your app process has stopped and restarted. you’ll see a message in the output similar to below:

PROCESS ENDED

Or:

PROCESS STARTED

Developers can fine tune the command to give the message timestamp, for example:

adb logcat -v time

Using logcat, you can determine whether a widget or component is declared but not defined yet, or a variable is null and being used. Sometimes, it could happen that a context is null during navigation between screens, and you are attempting to use that context without realizing it’s null.

Setting breakpoints to debug NullPointerException

If you have a large application, it can be quite cumbersome to debug it. You can set breakpoints in your code that let you debug your code block by block.

A breakpoint serves as a stop sign for the marked piece of code. When a breakpoint is encountered during application debugging, it will pause execution, thus enabling allowing developers to examine in detail what’s happening and use other debugging tools as required.

To use breakpoints, add a breakpoint by clicking the gutter in the code editor next to the line number where you want execution to pause. A dot will appear next to the line number, and the line will be highlighted. See below; two breakpoints are added:

Two breakpoints were added for debugging

Click Run > Debug ‘app’. The program halts at the first breakpoint and you can examine the values in the Debug window at the bottom of Android Studio:

The Debug window in Android Studio

There are various buttons such as Step Over and Step Into that can help you navigate further:

The Step Over and Step Into buttons

Besides examining the current values of certain operands and expressions, you can also evaluate expressions using the Evaluate option.

In the below example, I wanted to know what the value of x added to 100 would be. The window shows me the result based on the current value of x:

Getting the result of the current value of X

Here is a detailed explanation of various terms related to debugging in Android Studio.

Conclusion

To conclude, in Android development, there are various mechanisms available with Java and Kotlin that are designed to aid developers in avoiding NullPointerExceptions. In the cases these exceptions still occur, you should now have a variety of tools that help identify the cause and debug code.

LogRocket: Instantly recreate issues in your Android apps.

LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket’s product analytics features surface the reasons why users don’t complete a particular flow or don’t adopt a new feature.

Start proactively monitoring your Android apps — try LogRocket for free.

In this article, we will learn about null pointer exceptions in Java and look into some of the common errors that result in them. We will also see how we can prevent them from happening.

What is a Null Pointer Exception in Java?

The Null Pointer Exception is a runtime exception in Java. It is also called the unchecked exception as it escapes during compile-time but is thrown during runtime. A program throws this exception when it attempts to dereference an object that has a null reference.

Simply put, the null pointer exception is raised when we try to call a method or variable that has a null reference.

Let’s see an example,

class example{
  static String word = null;
  public static void main(String args[]){
    word = word.toUpperCase();
  }
}
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"String.toUpperCase()" because "example.word" is null at example.main(example.java:4)

From the above code, we see that when we call the String variable word to change to the upper case, we get a null pointer exception as word has a null reference.

Reasons for Null Pointer Exceptions

Some of the common mistakes that we may commit are:

  1. Invoking methods of a null object

    // Invoking methods of a null object
    class example1{
      void add(){
        int x = 4, y = 6;
        System.out.println(x+y); 
      }
      public static void main(String args[]){
        example1 obj = null;
        obj.add();
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot invoke "example1.add()"
    because "<local1>" is null at example1.main(example1.java:9)

    In line 9, we invoked the method add() of an object obj of class example1. Now, obj has a null reference, therefore we got a null pointer exception.

  2. Using or altering fields of a null object.

    // Using or altering fields of a null object
    class example2{
      int x = 10;
      public static void main(String args[]){
        example2 obj = null;
        int i = obj.x; // Accessing the field of a null object 
        obj.x = 20; // Modifying the field of a null object
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot read 
    field "x" because "<local1>" is null at example2.main(example2.java:6)

    Similar to example1, when the object obj of class example2 itself has a null reference then it is not possible to either access or modify its fields. The program threw a null pointer exception due to line 6.

  3. Calling length of a null array.

    // Calling length of a null array
    import java.util.*;
    class example3{
      public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        int arr[] = null;
        System.out.println(arr.length);
      }
    }
    
    Exception in thread "main" java.lang.NullPointerException: Cannot read the
    array length because "<local2>" is null at example3.main(example3.java:7)

    We created an integer array arr, but we assigned it to null which means that there is no information to store. Therefore, we got the null pointer exception when we tried to access the length of the null array.

  4. Using or altering the items of a null array.

    // Using or altering the items of a null array
    class example4{
      public static void main(String args[]){
        int arr[] = null;
        arr[2]=arr[3]+2;
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot load
    from int array because "<local2>" is null at example4.main(example4.java:7)

    Similar to example3, when there is no information in the array it is not possible to access or modify the elements that do not even exist. Therefore, a null pointer exception was thrown due to line 7.

  5. Throwing null value instead of a valid object.

    // Throwing null value instead of a valid object
    class example5{
      public static void main(String args[]){
        throw null;
      }
    }
    Exception in thread "main" java.lang.NullPointerException: Cannot throw exception
    because "null" is null at example5.main(example5.java:4)

    In this example, we tried to throw a null value instead of a valid object. Therefore, the null pointer exception was thrown.

Avoiding Null Pointer Exceptions

Let’s discuss some situations where we can carry out some steps to prevent null pointer exceptions. Of course, we must take care of all the above-mentioned reasons.

  1. Inspect the arguments passed to a method
    Sometimes, we may pass variables with null values to a method that results in a null pointer exception during runtime. It is always a better practice to check the arguments before proceeding to use them in the method.
    Let’s look at an example,

    class example_1{
      static int add(String s){
        try{
          System.out.println(s.concat("HI"));
        }catch(NullPointerException e){
          System.out.println("null value found");
        }
        return 6;
      }
      public static void main(String args[]){
        String word = null;
        System.out.println(add(word));
      }
    }
    null value found
    6

    s is assigned a null value. Since we checked on it before continuing, using a try-catch block, we did not encounter a null pointer exception.

  2. Use of ternary operators
    class example_2{  
    public static void main(String[] args){
      String word = null; 
      String output = (word == null) ? "null value" : word.toUpperCase();  
      System.out.println(output);  
      
      word = "code speedy";  
      output = (word == null) ? "null value" : word.toUpperCase();  
      System.out.println(output);  
      }  
    }
    null value
    CODE SPEEDY

    In line 4, we used the ternary operator to check if word is null. Since it is null, output will be “null value”. If we had not used the ternary operator then the program would have thrown the exception.

  3. To prefer valueOf() over toString()
    When we use toString() on a null object then the program throws the null pointer exception. Instead, we can get the same value by calling valueOf(). When the object passed has a null reference then valueOf() will return “null”, preventing the exception.
    For example,

    class example_3{
      public static void main(String args[]){
        String word = null;
        System.out.println("Using valueOf():n"+ String.valueOf(word)); // returns null
        System.out.println("Using toString():");
        System.out.println(word.toString()); // throws null pointer exception
      }
    }
    Using valueOf():
    null
    Using toString():
    Exception in thread "main" java.lang.NullPointerException: Cannot invoke
    "String.toString()" because "<local1>" is null at example_4.main(example_4.java:6)
  4. Another way to prevent null pointer exceptions is to prefer using primitive data types over the wrapper classes like Integer, Float, Double and BigDecimal.

I hope this article has helped you understand the null pointer exceptions in Java.

Also read: Java Exceptions , Errors , Exception Handling in Java

  • Ошибка null call of duty black ops 3 zombies
  • Ошибка ntvdm windows 7
  • Ошибка ntoskrnl exe windows 10 как исправить
  • Ошибка ntoskrnl exe 1d32e9
  • Ошибка ntldr is missing что делать