How to Handle Null Pointer Exception in Java
![]()
In Java, a special null value can be assigned to an object’s reference and denotes that the object is currently pointing to unknown piece of data. A NullPointerException is thrown when an application is trying to use or access an object whose reference equals to null . The following cases throw that exception:
- Invoking a method from a null object.
- Accessing or modifying a null object’s field.
- Taking the length of null , as if it were an array.
- Accessing or modifying the slots of null object, as if it were an array.
- Throwing null , as if it were a Throwable value.
- When you try to synchronize over a null object.
The NullPointerException is a RuntimeException and thus, the Javac compiler does not force you to use a try-catch block to handle it appropriately.
Why do we need the null value?
As already mentioned, null is a special value used in Java. It is extremely useful in coding some design patterns, such as Null Object pattern and Singleton pattern. The Null Object pattern provides an object as a surrogate for the lack of an object of a given type. The Singleton pattern ensures that only one instance of a class is created and also, aims for providing a global point of access to the object.
For example, a sample way to create at most one instance of a class is to declare all its constructors as private and then, create a public method that returns the unique instance of the class:
In this example, we declare a static instance of the Singleton class. That instance is initialized at most once inside the getInstance method. Notice the use of the null value that enables the unique instance creation.
How to avoid the NullPointerException
In order to avoid the NullPointerException , ensure that all your objects are initialized properly, before you use them. Notice that, when you declare a reference variable, you are really creating a pointer to an object. You must verify that the pointer is not null, before you request the method or a field from the object.
Also, if the exception is thrown, use the information residing in the exception’s stack trace. The execution’s stack trace is provided by the JVM, in order to enable the debugging of the application. Locate the method and the line where the exception was caught and then, figure out which reference equals to null in that specific line.
In the rest of this section, we will describe some techniques that deal with the aforementioned exception. However, they do not eliminate the problem and the programmer should always be careful while coding an application.
1. String comparison with literals
A very common case in an application’s execution code involves the comparison between a String variable and a literal. The literal may be a String or the element of an Enum. Instead of invoking the method from the null object, consider invoking it from the literal. For example, observe the following case:
The above code snippet will throw a NullPointerException . However, if we invoke the method from the literal, the execution flow continues normally:
2. Check the arguments of a method
Before executing the body of your own method, be sure to check its arguments for null values. Continue with the execution of the method, only when the arguments are properly checked. Otherwise, you can throw an IllegalArgumentException and notify the calling method that something is wrong with the passed arguments.
3. Prefer String.valueOf() method instead of toString()
When your application’s code requires the String representation of an object, avoid using the object’s toString method. If your object’s reference equals to null , a NullPointerException will be thrown.
Instead, consider using the static String.valueOf method, which does not throw any exceptions and prints "null" , in case the function’s argument equals to null .
4. Use the Ternary Operator
The ternary operator can be very useful and can help us avoid the NullPointerException . The operator has the form:
First, the boolean expression is evaluated. If the expression is true then, the value1 is returned, otherwise, the value2 is returned. We can use the ternary operator for handling null pointers as follows:
The message variable will be empty if str ’s reference is null. Otherwise, if str points to actual data, the message will retrieve the first 10 characters of it.
5. Create methods that return empty collections instead of null
A very good technique is to create methods that return an empty collection, instead of a null value. Your application’s code can iterate over the empty collection and use its methods and fields, without throwing a NullPointerException . For example:
6. Make use of Apache’s StringUtils class
Apache’s Commons Lang is a library that provides helper utilities for the java.lang API, such as String manipulation methods. A sample class that provides String manipulation is StringUtils.java , which handles null input Strings quietly.
You can make use of the StringUtils.isNotEmpty, StringUtils.IsEmpty and StringUtils.equals methods, in order to avoid the NullPointerException . For example:
7. Use the contains(), containsKey(), containsValue() methods
If your application code makes use of collections, such as Maps , consider using the contains, containsKey and containsValue methods. For example, retrieve the value of a specific key, after you have verified its existence in the map:
In the above snippet, we don’t check if the key actually exists inside the Map and thus, the returned value can be null . The safest way is the following:
8. Check the return value of external methods
It is very common in practice to make use of external libraries. These libraries contain methods that return a reference. Make sure that the returned reference is not null . Also, consider reading the Javadoc of the method, in order to better understand its functionality and its return values.
9. Use Assertions
Assertions are very useful while testing your code and can be used, in order to avoid executing code snippets that will throw a NullPointerException . Java Assertions are implemented with the assert keyword and throw an AssertionError .
Notice that you must explicitly enable the assertion flag of the JVM, by executing it with the –ea argument. Otherwise, the assertions will be completely ignored.
A sample example using Java assertions is the following:
If you execute the above code snippet and pass a null argument to getLength , the following error message will appear:
Exception in thread "main" java.lang.AssertionError
Finally, you can use the Assert class provided by the jUnit testing framework.
10. Unit Tests
Unit tests can be extremely useful while testing the functionality and correctness of your code. Devote some time to write a couple tests cases that verify that no NullPointerException is thrown, while your application’s code undergoes a specific execution flow.
Existing NullPointerException safe methods
1. Accessing static members or methods of a class
When your code attempts to access a static variable or method of a class, even if the object’s reference equals to null , the JVM does not throw a NullPointerException . This is due to the fact that the Java compiler stores the static methods and fields in a special place, during the compilation procedure. Thus, the static fields and methods are not associated with objects, rather with the name of the class.
For example, the following code does not throw a NullPointerException :
Notice, that despite the fact that the instance of the SampleClass equals to null , the method will be executed properly. However, when it comes to static methods or fields, it is better to access them in a static way, such as SampleClass.printMessage() .
2. The instanceof operator
The instanceof operator can be used, even if the object’s reference equals to null . The instanceof operator returns false when the reference equals to null and does not throw a NullPointerException . For example consider the following code snippet:
Как исправить ошибку java.lang.nullpointerexception?
В этом посте я покажу наглядный пример того, как исправить ошибку исключения Null Pointer (java.lang.nullpointerexception). В Java особое значение null может быть назначено для ссылки на объект и означает, что объект в данный момент указывает неизвестную область данных.
NullPointerException появляется, если программа обращается или получает доступ к объекту, а ссылка на него равна нулю (null).
Это исключение возникает следующих случаях:
- Вызов метода из объекта значения null.
- Доступ или изменение объекта поля null.
- Принимает длину null(если бы это был массив Java).
- Доступ или изменение ячеек объекта null.
- Показывает «0», значение Throwable.
- При попытке синхронизации по нулевому объекту.
NullPointerException является RuntimeException, и, таким образом, компилятор Javac не заставляет вас использовать блок try-catch для соответствующей обработки.

Зачем нам нужно значение null?
Как уже упоминалось, null – это специальное значение, используемое в Java. Это чрезвычайно полезно при кодировании некоторых шаблонов проектирования, таких как Null Object pattern и шаблон Singleton pattern.
Шаблон Singleton обеспечивает создание только одного экземпляра класса, а также направлен на предоставление глобального доступа к объекту.
Например, простой способ создания не более одного экземпляра класса – объявить все его конструкторы как частные, а затем создать открытый метод, который возвращает уникальный экземпляр класса:
В этом примере мы объявляем статический экземпляр класса Singleton. Этот экземпляр инициализируется не более одного раза внутри метода getInstance.
Обратите внимание на использование нулевого значения, которое разрешает создание уникального экземпляра.
Как избежать исключения Null Pointer
Чтобы решить и избежать исключения NullPointerException, убедитесь, что все ваши объекты инициализированы должным образом, прежде чем использовать их.
Когда вы объявляете ссылочную переменную, вы должны создать указатель на объект и убедиться, что указатель не является нулевым, прежде чем запрашивать метод или поле у объекта.
Кроме того, если выдается исключение, используйте информацию, находящуюся в трассировке стека исключения. Трассировка стека выполнения обеспечивается JVM, чтобы включить отладку. Найдите метод и строку, в которой было обнаружено исключение, а затем выясните, какая ссылка равна нулю в этой конкретной строке.
Опишем некоторые методы, которые имеют дело с вышеупомянутым исключением. Однако они не устраняют проблему, и программист всегда должен быть осторожен.
- Сравнение строк с литералами
Очень распространенный случай, выполнения программы включает сравнение между строковой переменной и литералом. Литерал может быть строкой или элементом Enum.
Вместо того, чтобы вызывать метод из нулевого объекта, рассмотрите возможность вызова его из литерала. Например:
Приведенный выше фрагмент кода вызовет исключение NullPointerException. Однако, если мы вызываем метод из литерала, поток выполнения продолжается нормально:
- Проверка аргументов метода
Перед выполнением вашего собственного метода обязательно проверьте его аргументы на наличие нулевых значений.
В противном случае вы можете вызвать исключение IllegalArgumentException.
- Предпочтение метода String.valueOf() вместо of toString()
Когда код вашей программы требует строковое представление объекта, избегайте использования метода toString объекта. Если ссылка вашего объекта равна нулю, генерируется исключение NullPointerException.
Вместо этого рассмотрите возможность использования статического метода String.valueOf, который не выдает никаких исключений и «ноль», если аргумент функции равен нулю.
- Используйте 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 символов.
- создайте методы, которые возвращают пустые коллекции вместо нуля.
Очень хорошая техника – создавать методы, которые возвращают пустую коллекцию вместо нулевого значения. Код вашего приложения может перебирать пустую коллекцию и использовать ее методы и поля. Например:
- Воспользуйтесь классом Apache’s StringUtils.
Apache’s Commons Lang – это библиотека, которая предоставляет вспомогательные утилиты для API java.lang, такие как методы манипулирования строками.
Примером класса, который обеспечивает манипулирование String, является StringUtils.java, который спокойно обрабатывает входные строки с нулевым значением.
Вы можете воспользоваться методами: StringUtils.isNotEmpty, StringUtils.IsEmpty и StringUtils.equals, чтобы избежать NullPointerException. Например:
- Используйте методы: contains(), containsKey(), containsValue()
Если в коде вашего приложения используется Maps, рассмотрите возможность использования методов contains, containsKey и containsValue. Например, получить значение определенного ключа после того, как вы проверили его существование на карте:
System.out.println(value.toString()); // В приведенном выше фрагменте мы не проверяем, существует ли на самом деле ключ внутри карты, и поэтому возвращаемое значение может быть нулевым. Самый безопасный способ следующий:
- Проверьте возвращаемое значение внешних методов
На практике очень часто используются внешние библиотеки. Эти библиотеки содержат методы, которые возвращают ссылку. Убедитесь, что возвращаемая ссылка не пуста.
- Используйте Утверждения
Утверждения очень полезны при тестировании вашего кода и могут использоваться, чтобы избежать выполнения фрагментов кода. Утверждения Java реализуются с помощью ключевого слова assert и выдают AssertionError.
Обратите внимание, что вы должны включить флажок подтверждения JVM, выполнив его с аргументом -ea. В противном случае утверждения будут полностью проигнорированы.
Примером использования утверждений Java является такая версия кода:
Если вы выполните приведенный выше фрагмент кода и передадите пустой аргумент getLength, появится следующее сообщение об ошибке:
Exception in thread «main» java.lang.AssertionError
Также вы можете использовать класс Assert предоставленный средой тестирования jUnit.
- Модульные тесты
Модульные тесты могут быть чрезвычайно полезны при тестировании функциональности и правильности вашего кода. Уделите некоторое время написанию пары тестовых примеров, которые подтверждают, что исключение NullPointerException не возникает.
Существующие безопасные методы NullPointerException
Доступ к статическим членам или методам класса
Когда ваш вы пытаетесь получить доступ к статической переменной или методу класса, даже если ссылка на объект равна нулю, JVM не выдает исключение.
Это связано с тем, что компилятор Java хранит статические методы и поля в специальном месте во время процедуры компиляции. Статические поля и методы связаны не с объектами, а с именем класса.
Несмотря на тот факт, что экземпляр SampleClass равен нулю, метод будет выполнен правильно. Однако, когда речь идет о статических методах или полях, лучше обращаться к ним статическим способом, например, SampleClass.printMessage ().
Оператор instanceof
Оператор instanceof может использоваться, даже если ссылка на объект равна нулю.
Оператор instanceof возвращает false, когда ссылка равна нулю.
В результате, как и ожидалось:
Not an instance of the String class!
Смотрите видео, чтобы стало понятнее.
Средняя оценка 4.1 / 5. Количество голосов: 10
Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.
Или поделись статьей
Видим, что вы не нашли ответ на свой вопрос.
Помогите улучшить статью.
Напишите комментарий, что можно добавить к статье, какой информации не хватает.
How to Fix and Avoid NullPointerException in Java

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:
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 :
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:
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:
- Making sure an object is initialized properly by adding a null check before referencing its methods or properties.
- Using Apache Commons StringUtils for String operations e.g. using StringUtils.isNotEmpty() for verifying if a string is empty before using it further.
- 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
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!
Что такое Null Pointer Exception и как его исправить?
Что из себя представляет исключение Null Pointer Exception ( java.lang.NullPointerException ) и почему оно может происходить?
Какие методы и средства использовать, чтобы определить причину возникновения этого исключения, приводящего к преждевременному прекращению работы приложения?
![]()
![]()
Когда вы объявляете переменную ссылочного типа, на самом деле вы создаете ссылку на объект данного типа. Рассмотрим следующий код для объявления переменной типа int:
В этом примере переменная x имеет тип int и Java инициализирует её как 0. Когда вы присвоите переменной значение 10 (вторая строка), это значение сохранится в ячейке памяти, на которую ссылается x .
Но когда вы объявляете ссылочный тип, процесс выглядит иначе. Посмотрим на следующий код:
В первой строке объявлена переменная num , ее тип не относится к встроенному, следовательно, значением является ссылка (тип этой переменной, Integer , является ссылочным типом). Поскольку вы еще не указали, на что собираетесь ссылаться, Java присвоит переменной значение Null , подразумевая «Я ни на что не ссылаюсь».
Во второй строке, ключевое слово new используется для создания объекта типа Integer . Этот объект имеет адрес в памяти, который присваивается переменной num . Теперь, с помощью переменной num вы можете обратиться к объекту используя оператора разыменования . .
Исключение, о котором вы говорите в вопросе, возникает, если вы объявили переменную, но не создали объект, то есть если вы попытаетесь разыменовать num до того, как создали объект, вы получите NullPointerException . В самом простом случае, компилятор обнаружит проблему и сообщит, что
num may not have been initialized
Что говорит: «возможно, переменная num не инициализирована».
Иногда исключение вызвано именно тем, что объект действительно не был создан. К примеру, у вас может быть следующая функция:
В этом случае создание объекта (переменная num ) лежит на вызывающем коде, то есть вы предполагаете, что он был создан ранее – до вызова метода doSomething . К сожалению, следующий вызов метода вполне возможен:
В этом случае значение переменной num будет null . Лучшим способом избежать данного исключения будет проверка на равенство нулю. Как результат, функция doSomething должна быть переписана следующим образом:
Как альтернативный вариант предыдущему примеру вы можете сообщить вызывающему коду, что метод был вызван с неверными параметрами, например, с помощью IllegalArgumentException .