Если вы сталкивались с ошибками Exception in thread “main”, то в этой статье я расскажу что это значит и как исправить ее на примерах.
При работе в среде Java, типа Eclipse или Netbeans, для запуска java-программы, пользователь может не столкнуться с этой проблемой, потому что в этих средах предусмотрен качественный запуск с правильным синтаксисом и правильной командой.
Здесь мы рассмотрим несколько общих java-исключений(Exceptions) в основных исключениях потоков, которые вы можете наблюдать при запуске java-программы с терминала.
Это исключение происходит, когда ваш класс java компилируется из другой версии JDK и вы пытаетесь запустить его из другой версии java. Рассмотрим это на простом примере:
package com.journaldev.util;
public class ExceptionInMain {
public static void main() {
System.out.println(10);
}
}
Когда создаётся проект в Eclipse, он поддерживает версию JRE, как в Java 7, но установлен терминал Jawa 1.6. Из-за настройки Eclipse IDE JDK, созданный файл класса компилируется с Java 1.7.
Теперь при попытке запустить эту версию с терминала, программа выдает следующее сообщение исключения.
pankaj@Pankaj:~/Java7Features/bin$java com/journaldev/util/ExceptionInMain Exception in thread "main" java.lang.UnsupportedClassVersionError: com/journaldev/util/ExceptionInMain : Unsupported major.minor version 51.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631) at java.lang.ClassLoader.defineClass(ClassLoader.java:615) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141) at java.net.URLClassLoader.defineClass(URLClassLoader.java:283) at java.net.URLClassLoader.access$000(URLClassLoader.java:58) at java.net.URLClassLoader$1.run(URLClassLoader.java:197) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Если запустить версию Java1.7, то это исключение не появится. Смысл этого исключения – это невозможность компилирования java-файла с более свежей версии на устаревшей версии JRE.
Исключение java.lang.NoClassDefFoundError
Существует два варианта. Первый из них – когда программист предоставляет полное имя класса, помня, что при запуске Java программы, нужно просто дать имя класса, а не расширение.
Обратите внимание: если написать: .class в следующую команду для запуска программы – это вызовет ошибку NoClassDefFoundError. Причина этой ошибки — когда не удается найти файл класса для выполнения Java.
pankaj@Pankaj:~/CODE/Java7Features/bin$java com/journaldev/util/ExceptionInMain.class Exception in thread "main" java.lang.NoClassDefFoundError: com/journaldev/util/ExceptionInMain/class Caused by: java.lang.ClassNotFoundException: com.journaldev.util.ExceptionInMain.class at java.net.URLClassLoader$1.run(URLClassLoader.java:202) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:190) at java.lang.ClassLoader.loadClass(ClassLoader.java:306) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Второй тип исключения происходит, когда Класс не найден.
pankaj@Pankajs-MacBook-Pro:~/CODE/Java7Features/bin/com/journaldev/util$java ExceptionInMain Exception in thread "main" java.lang.NoClassDefFoundError: ExceptionInMain (wrong name: com/journaldev/util/ExceptionInMain) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:791) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:423) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:356) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:480)
Обратите внимание, что класс ExceptionInMain находится в пакете com.journaldev.util, так что, когда Eclipse компилирует этот класс, он размещается внутри /com/journaldev/util. Следовательно: класс не найден. Появится сообщение об ошибке.
Подробнее узнать об ошибке java.lang.NoClassDefFoundError.
Исключение java.lang.NoSuchMethodError: main
Это исключение происходит, когда вы пытаетесь запустить класс, который не имеет метод main. В Java.7, чтобы сделать его более ясным, изменяется сообщение об ошибке:
pankaj@Pankaj:~/CODE/Java7Features/bin$ java com/journaldev/util/ExceptionInMain Error: Main method not found in class com.journaldev.util.ExceptionInMain, please define the main method as: public static void main(String[] args) Exception in thread "main" java.lang.ArithmeticException
Всякий раз, когда происходит исключение из метода main – программа выводит это исключение на консоль.
В первой части сообщения поясняется, что это исключение из метода main, вторая часть сообщения указывает имя класса и затем, после двоеточия, она выводит повторно сообщение об исключении.
Например, если изменить первоначальный класс появится сообщение System.out.println(10/0); Программа укажет на арифметическое исключение.
Exception in thread "main" java.lang.ArithmeticException: / by zero at com.journaldev.util.ExceptionInMain.main(ExceptionInMain.java:6)
Методы устранения исключений в thread main
Выше приведены некоторые из распространенных исключений Java в потоке main, когда вы сталкиваетесь с одной из следующих проверок:
- Эта же версия JRE используется для компиляции и запуска Java-программы.
- Вы запускаете Java-класс из каталога классов, а пакет предоставляется как каталог.
- Ваш путь к классу Java установлен правильно, чтобы включить все классы зависимостей.
- Вы используете только имя файла без расширения .class при запуске.
- Синтаксис основного метода класса Java правильный.
Время на прочтение
5 мин
Количество просмотров 269K
Эта простая статья скорее для начинающих разработчиков Java, хотя я нередко вижу и опытных коллег, которые беспомощно глядят на stack trace, сообщающий о NullPointerException (сокращённо NPE), и не могут сделать никаких выводов без отладчика. Разумеется, до NPE своё приложение лучше не доводить: вам помогут null-аннотации, валидация входных параметров и другие способы. Но когда пациент уже болен, надо его лечить, а не капать на мозги, что он ходил зимой без шапки.
Итак, вы узнали, что ваше приложение упало с NPE, и у вас есть только stack trace. Возможно, вам прислал его клиент, или вы сами увидели его в логах. Давайте посмотрим, какие выводы из него можно сделать.
NPE может произойти в трёх случаях:
- Его кинули с помощью throw
- Кто-то кинул null с помощью throw
- Кто-то пытается обратиться по null-ссылке
Во втором и третьем случае message в объекте исключения всегда null, в первом может быть произвольным. К примеру, java.lang.System.setProperty кидает NPE с сообщением «key can’t be null», если вы передали в качестве key null. Если вы каждый входной параметр своих методов проверяете таким же образом и кидаете исключение с понятным сообщением, то вам остаток этой статьи не потребуется.
Обращение по null-ссылке может произойти в следующих случаях:
- Вызов нестатического метода класса
- Обращение (чтение или запись) к нестатическому полю
- Обращение (чтение или запись) к элементу массива
- Чтение length у массива
- Неявный вызов метода 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 будет указывать на строку с вызовом.
В заключение хочется пожелать пореже запускать отладчик: после некоторой тренировки анализ кода в голове нередко выполняется быстрее, чем воспроизведение трудноуловимой ситуации.
I’ve just created a project on Eclipse and imported some source files (existing project). But I can’t compile it ! Ok, the project has got several source files, so I wanted to compile only the Main.java file (with eclipse not in the command line, in the command line it worked!) but all what I get is this error :
As you can see the Main.java file is straighforward, just a hello world !
What’s the matter ?
Thanks
asked Dec 13, 2009 at 17:35
Amokrane ChentirAmokrane Chentir
29.8k37 gold badges114 silver badges158 bronze badges
2
«Unresolved compilation problem» means that the class hasn’t compiled successfully. Eclipse will still let you run code that doesn’t compile, but any of the specific bits which don’t compile will throw this error. Look in the «Problems» tab to see what’s wrong.
From the look of the Package Explorer view, every single class has a problem… perhaps the file location doesn’t match the package declaration? That would match the position of the pink box just to the right of the vertical scrollbar for the class — it suggests that the error is right at the top of the file, which is where the package declaration would be.
answered Dec 13, 2009 at 17:40
Jon SkeetJon Skeet
1.4m861 gold badges9099 silver badges9172 bronze badges
3
You have a compilation error at the top of your Main.java file, just out of sight in the screenshot. Probably an unresolvable import or a wrong/missing package declaration.
answered Dec 13, 2009 at 17:43
Michael BorgwardtMichael Borgwardt
341k78 gold badges482 silver badges719 bronze badges
1
It is simple in my case that the imported project needs 32 bit jre to run but cannot be compiled in the same. In IDE, if you click run, it will try to compile and run the project in single shot so fails due to 32 bit jre for compilation with the above reported error.
So i used 64 bit compiler and started to run and got compiled successfully but thrown error that needs 34 bit jre for some of the SWT used in the project. Again i changed the 32 bit jre and run the project, it is gone ! THE ERROR IS GONE NOW !
answered Mar 6, 2019 at 15:10
You can get the error «Exception in thread «main»
java.lang.Error: Unresolved compilation problem:» if your public class name differs from your file name.
example:
File Name:
ServiceRequest.java
Inside file, class is named differently; like
public class Service
answered May 9, 2019 at 20:32
Tom StickelTom Stickel
19.5k6 gold badges111 silver badges113 bronze badges
Делаю задачу в Intellij IDEA, при запуске дает ввести первую строку, при нажатии enter выдает исключение :
Exception in thread «main» java.lang.NumberFormatException: For input string: «string»
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at com.javarush.task.task07.task0706.Solution.main(Solution.java:19)
Process finished with exit code 1
Это происходит уже не с первой задачей, такое ощущение, что проверка запускается не для текущей задачи, а для одной из выполненных перед ней. Я пробовала удалить плагин javarush и установить его заново, ничего не поменялось, не пойму, почему так происходит или действительно ошибка в текущей задаче.
package com.javarush.task.task07.task0711;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Удалить и вставить
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList <String> list = new ArrayList <String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < 5; i++) {
String s = reader.readLine();
list.add(s);
}
for (int i = 0; i < 13; i++) {
list.get(list.size() — 1);
list.remove(list.size() — 1);
list.set(0, list.get(list.size() — 1));
}
for (int i = 0; i < list.size(); i++) {
System.out.println (list.get(i));
}
}
}

Thus, in Java, if you run the program in this syntax, then NullPointerException will be shown every time. Keep reading more for better understanding!
Contents
- Why Does Exception in Thread Main Java Lang Nullpointerexception Error Occur?
- – Calling the Instance Method of a Null Object
- – Trying to Access or Modify the Field of a Null Object
- – Using the Length of Null as an Array
- – Access or Modify the Null Object Slots as an Array.
- – Throwing the Null Object Like It’s a Throwable Value
- – Add Null to Collections That Don’t Allow Nulls; “Concurrenthashmap”
- – Synchronize Using the Null Object
- How To Resolve NullPointerException Error in Java Programming Language
- – String Comparison Method
- – Using the “Optional” Method
- – Use Ternary Operator
- – Check on the Arguments of the Method
- – Use Stringutils
- – Detect the Nullpointerexception Issue
- – Fix a Null Pointer Exception
- – Do a Null Check
- FAQs
- – How Does the Java Program Handle the “Nullpointerexception” Error for Integers?
- – Why Is There an Exception in the Thread “Main” Error in Java Program?
- – What Does the Exception in Thread Main Java Lang Nullpointerexception Error Mean?
- – How To Stop Nullpointerexception Error From Occurring in Java?
- – What Is a Nullpointerexception and How Do I Fix This Issue?
- Conclusion
There are multiple reasons why this issue can arise in the Java programming language. The few listed below are the most major and common human errors that cause this. Let’s create a Student class example to explain each reason in detail.
Program:
package org.arpit.java2blog;
public class Student {
String name;
int age;
public Student()
{
}
public Student(String name, int age) {
this.name=name;
this.age=age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
– Calling the Instance Method of a Null Object
package org.arpit.java2blog;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
Student s1=null;
String name = s1.getName();
System.out.println(“Student Name: “+ name);
}
}
As soon as you press enter after that syntax, you will see this message on screen.
Exception in thread “main” java.lang.NullPointerException at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)”
As you can see the full-highlighted line, s1 is null and the program used getMethod on it, that’s why this issue or error was shown here.
– Trying to Access or Modify the Field of a Null Object
package org.arpit.java2blog;
public class NullFieldExampleMain {
public static void main(String[] args) {
Student s1=null;
String name = s1.name;
System.out.println(“Employee Name: “+ name);
}
}
As you can notice again in the highlighted line, s1 is null and the user accessed the name field of s1. Thus, the error will arise.
– Using the Length of Null as an Array
package org.arpit.java2blog;
public class NullArrayLengthMain {
public static void main(String[] args) {
Student[] arrEmp=null;
int length = arrEmp.length;
System.out.println(“Length of array: “+length);
}
}
Again, the error will arise because of the null.
– Access or Modify the Null Object Slots as an Array.
Let’s see where the problem occurs if you use the null object in java using access or modify the null slot in the array.
package org.arpit.java2blog;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
Student[] arrEmp=null;
System.out.println(arrEmp[3]);
}
}
As you can see the problem lies in the last syntax “System.out.println(arrEmp[3])”. Java program will show us an “Exception in thread “main” java.lang.NullPointerException” message because “3” is not recognized by the java program.
– Throwing the Null Object Like It’s a Throwable Value
package org.arpit.java2blog;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
throw null;
}
}
The error will arise again.
– Add Null to Collections That Don’t Allow Nulls; “Concurrenthashmap”
package org.arpit.java2blog;
import java.util.concurrent.ConcurrentHashMap;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>();
map.put(null, “Dummy”);
}
}
When you run this program, an error will occur because you didn’t address “Dummy” in the Null slot, so java didn’t recognize it.
– Synchronize Using the Null Object
package org.arpit.java2blog;
import java.util.concurrent.ConcurrentHashMap;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
Object obj=null;
synchronized (obj) {
ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>();
map.put(“Dummy”, “value”);
}
}
}
After running this program, the “Exception in thread “main” java.lang.NullPointerException” message will be shown to us on screen.
How To Resolve NullPointerException Error in Java Programming Language
There are multiple ways of resolving this issue. Let’s discuss them below using the same example as taken before.
– String Comparison Method
This is the most frequently occurring reason for Exception in thread “main” java.lang.NullPointerException error. Let’s understand this with the help of an example.
package org.arpit.java2blog;
public class StringComparisonMain {
public static void main(String[] args) {
Student s1=new Student();
if(s1.getName().equalsIgnoreCase(“Amber”))
{
System.out.println(“Student Name is Amber”);
}
}
}
After running this program you will receive a NullPointerException error here. This is because you didn’t set the name of the student s1.
To solve this error, you have to use the following correct method:
package org.arpit.java2blog;
public class StringComparisonMain {
public static void main(String[] args) {
Student s1=new Student();
if(“Amber”.equalsIgnoreCase(s1.getName()))
{
System.out.println(“Student Name is Amber”);
}
}
}
This will avoid the NullPointerException error after the running of this program.
– Using the “Optional” Method
“Optional” is a new class name that java 8 has introduced. Usually, there are no values in the method. You just return null from it and it gets hard for the caller to check for null. For instance, let’s see the below example;
public static Student findStudent(List<Student studentList,String name)
{
for(Student s:studentList)
{
if(s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
As you can notice here, the user did not find the student in “studentList”. The user is directly returning null from the “findStudent()” method. The caller will use a student object from the “findStudent()” method and may call the getName() method as well. Due to this, the user will get a NullPointerException error message in return.
For such problems, the Optional method is best to use and solve exception errors. See the following example carefully;
package org.arpit.java2blog;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class JavaOptionalMain {
public static void main(String[] args)
{
List<Student> studentList = createStudentList();
Optional<Student> studentOpt = findStudent(studentList,”Amber”);
if(studentOpt.isPresent())
{
Student student = studentOpt.get();
System.out.println(“Student name: “+student.getName());
}
else
{
System.out.println(“There is no student with the name Amber”);
}
}
public static Optional<Student> findStudent(List<Student> studentList,String name)
{
for(Student s:studentList)
{
if(s.getName().equalsIgnoreCase(name))
{
return Optional.of(s);
}
}
return Optional.empty();
}
public static List<Student> createStudentList()
{
List<Student> studentList=new ArrayList<>();
Student s1=new Student(“Josh”,23);
Student s2=new Student(“David”,20);
Student s3=new Student(“Caroline”,24);
Student s4=new Student(“Mehmet”,25);
Student s5=new Student(“Kate”,22);
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
studentList.add(s4);
studentList.add(s5);
return studentList;
}
}
After running the program, the error will be resolved and you’ll receive a message as intended to get when you started writing the program. That is, “There is no student with the name Amber”. It indicates to the caller that the returned value can be null.
– Use Ternary Operator
You can also use the “Ternary Operator” to check for null. Let’s see the following program;
package org.arpit.java2blog;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
Student s1=null;
String name = s1==null?s1.getName():””;
System.out.println(“Student Name: “+ name);
}
}
Now you will not get the error after running this program.
– Check on the Arguments of the Method
This is another method to stop the error from arising in a java program. Let’s learn this through an example;
package org.arpit.java2blog;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
String zab=null;
int len=getLength(zab);
System.out.println(“Length of String:”+ len);
}
public static int getLength(String zab)
{
if(zab!=null)
{
return zab.length();
}
else
{
return 0;
}
}
}
After running the program, no error will arise.
– Use Stringutils
A lot of empty String checks can be done by the StringUtils class in the java program. If you need to check the string to see if it’s null or empty, you can use the “isEmpty” method from “StringUtils”. It will take care of the problem. It makes the programmer’s work much easier than before.
– Detect the Nullpointerexception Issue
It is easy to detect this error in the Java programming language. The software will show you the Exception trace and you have to follow it to see in which class name and line number of the exception the error exists. Then check the code and see if null is causing this NullPointerException message to appear.
– Fix a Null Pointer Exception
To identify the exact fix for a Null Pointer Exception,
- You have to notice the situation and code because it is different for different codes and situations.
- The biggest reason for a Null Pointer Exception to occur is due to the human error done while typing the program. Thus, check your syntax.
- Ensure that the program you wrote carries the correct logic that you had initially intended to type.
- The exception in thread “main” java.lang.nullpointerexception is a somewhat common error or an exception that occurs when you try to run a program with an object that has a null value.
- The “main” in the error means that the exception is in the main thread. Calling the length of an array if the array is null.
– Do a Null Check
Let’s check null before using the invoking method or field.
package org.arpit.java2blog;
public class InvokingMethodOnNullMain {
public static void main(String[] args) {
Student s1=null;
if(s1!=null)
{
String name = s1.getName();
System.out.println(“Employee Name: “+ name);
}
}
}
Now, when you run this program, you will not get a NullPointerException error message. This happens because of the syntax you used here; “if(s1!=null)”.
FAQs
– How Does the Java Program Handle the “Nullpointerexception” Error for Integers?
There are several ways java users can use to handle the “NullPointerException” error for integers. They are listed below:
- Check every object fur null before using.
- Use and check Method Arguments for null.
- Use primitives rather than objects.
- Use Chained Method calls.
- Make the NullPointerExceptions Informative.
– Why Is There an Exception in the Thread “Main” Error in Java Program?
Sometimes while writing a program in java, you get this error showing us that there’s an error in the main thread. That “main” is showing you that the error is in the main thread of the program.
Java looks for the “.class” files in the current dictionary. So if, for example, the “.class” file is in C:java, then change the current directory to that as well, otherwise it will show the exception in thread “main” error at the time of program run. To change the dictionary, type the command “C:java” at the prompt and press Enter.
– What Does the Exception in Thread Main Java Lang Nullpointerexception Error Mean?
The Null Pointer Exception is one of the many other Exceptions supported by the Java programming language. This error indicates that there was an attempt made to access a reference variable that points to null.
– How To Stop Nullpointerexception Error From Occurring in Java?
To avoid the NullPointerException error, you must ensure that all the objects are initialized properly, before using them. When you write a reference variable, you have to verify that the object is not null, before you request a method or a field from the object. Check the syntax error and correct it. You’ll be able to avoid this programming error.
– What Is a Nullpointerexception and How Do I Fix This Issue?
NullPointerException is shown to the user when a reference variable is accessed (or de-referenced) and is not pointing to any object or is null, without any reference. This error can be resolved by using a try-catch block or an if-else condition to check if the reference variable is null before dereferencing it.
Conclusion
After reading through this blog, you know what is the exception in thread “main” java lang Nullpointerexception error, why it occurs and how you can solve this error. Here’s the recap of the article;
- Exception in thread “main” java lang nullpointerexception is an error that occurs due to a wrong syntax; a[] = null.
- Use the “isEmpty” Method from “StringUtils” to avoid Nullpointerexception errors faster.
- Exception trace error will be shown to you by the software itself. The user has to see in which class name and line number of the exception the error exists. Then fix it manually.
After reading this article you should know how you can resolve your Exception error. Thank you for reading!
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
Table of Contents
- Reasons for NullPointerException
- 1. Invoking the instance method of a null object
- 2. Accessing or modifying the field of a null object.
- 3. Taking the length of null as if it were an array.
- 4. Accessing or modifying the slots of null as if it were an array.
- 5. Throwing null as if it were a Throwable value.
- 6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap
- 7. Trying to synchronize using null object.
- Detection of NullPointerException
- Fix NullPointerException
- 1. Null check
- 2. Do null check as well before putting key or value in Collection which do not allow null
- Best practices for avoiding NullPointerException
- 1. String comparison
- 2. Use Optional
- 3. Use ternary opertor
- 4. Keep check on arguments of method
- 5. Use StringUtils from Apache Common
In this tutorial, we will see the most frequent java exception i.e. Exception in thread main java.lang.NullPointerException. It is one of the Runtime Exception.
Raise your hand if you ever got NullPointerException while working on java code. I am sure that this is the exception you might have encountered most frequently. You might also agree that NullPointerException is pain for most of java developers(novice or expert), but there is not much we can do about them, because this is the price we need to pay for convenient or unavoidable null references.
Reasons for NullPointerException
Reasons for NullPointerException as defined by Java docs.
- Invoking the instance method of a null object.
- Accessing or modifying the field of a null object.
- Taking the length of null as if it were an array.
- Accessing or modifying the slots of null as if it were an array.
- Throwing null as if it were a Throwable value.
- When you add null to Collections which do not allow nulls such as [ConcurrentHashMap](https://java2blog.com/concurrenthashmap-in-java/ “ConcurrentHashMap”)
- Trying to synchronize using null object.
Let’s understand each of these in detail. I am creating a Employee class which we are going to use in our examples.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package org.arpit.java2blog; public class Employee { String name; int age; public Employee() { } public Employee(String name, int age) { this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } |
1. Invoking the instance method of a null object
This is most obvious one.
|
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee e1=null; String name = e1.getName(); System.out.println(«Employee Name: «+ name); } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)
As you can see, e1 is null at line 7 and we are calling getMethod on it, thats why we are getting Exception in thread " main java.lang.NullPointerException here.
2. Accessing or modifying the field of a null object.
It is very much similar to calling instance method on null.
|
package org.arpit.java2blog; public class NullFieldExampleMain { public static void main(String[] args) { Employee e1=null; String name = e1.name; System.out.println(«Employee Name: «+ name); } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.NullFieldExampleMain.main(InvokingMethodOnNullMain.java:8)
As you can see, e1 is null at line 8 and we are accessing name field of e1, thats why we are getting NullPointerException here.
3. Taking the length of null as if it were an array.
When you try to get length of null array, you will get NullPointerException.
|
package org.arpit.java2blog; public class NullArrayLengthMain { public static void main(String[] args) { Employee[] arrEmp=null; int length = arrEmp.length; System.out.println(«Length of array: «+length); } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.NullArrayLengthMain.main(InvokingMethodOnNullMain.java:9)
4. Accessing or modifying the slots of null as if it were an array.
When you try to access or modify null slot in array.Let’s understand with the help of example.
|
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee[] arrEmp=null; System.out.println(arrEmp[3]); } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:8)
5. Throwing null as if it were a Throwable value.
When you throw null as Throwable.
|
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { throw null; } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:7)
6. When you add null to Collections which do not allow nulls such as ConcurrentHashMap
|
package org.arpit.java2blog; import java.util.concurrent.ConcurrentHashMap; public class InvokingMethodOnNullMain { public static void main(String[] args) { ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>(); map.put(null, «Dummy»); } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at java.base/java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1022)
at java.base/java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1017)
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)
7. Trying to synchronize using null object.
When you synchronize on null object, you will get NullPointerException
|
package org.arpit.java2blog; import java.util.concurrent.ConcurrentHashMap; public class InvokingMethodOnNullMain { public static void main(String[] args) { Object obj=null; synchronized (obj) { ConcurrentHashMap<String, String> map=new ConcurrentHashMap<>(); map.put(«Dummy», «value»); } } } |
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.InvokingMethodOnNullMain.main(InvokingMethodOnNullMain.java:10)
Detection of NullPointerException
It is easier to detect NullPointerException. Check exception trace, it will tell you class name, method name and line number.Go to that line number and check what can be the reason for NullPointerException.
Let’s take above scenrios and fix NullPointerException.
1. Null check
check null before calling method or field.
|
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee e1=null; if(e1!=null) { String name = e1.getName(); System.out.println(«Employee Name: «+ name); } } } |
When you run above program, you won’t get NullPointerExcpetion.
2. Do null check as well before putting key or value in Collection which do not allow null
Best practices for avoiding NullPointerException
1. String comparison
This is most frequent reason for Exception in thread main java.lang.NullPointerException, let’s understand with the help of example.
|
package org.arpit.java2blog; public class StringComparisonMain { public static void main(String[] args) { Employee e1=new Employee(); if(e1.getName().equalsIgnoreCase(«John»)) { System.out.println(«Employee Name is John»); } } } |
As we did not set name of Employee e1, we will get NullPointerException here.
When you run above program, you will get below output.
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.StringComparisonMain.main(StringComparisonMain.java:8)
You can change logic as below.
|
package org.arpit.java2blog; public class StringComparisonMain { public static void main(String[] args) { Employee e1=new Employee(); if(«John».equalsIgnoreCase(e1.getName())) { System.out.println(«Employee Name is John»); } } } |
This will avoid Exception in thread main java.lang.NullPointerException.
Please note that it may cause unexpected behavior due to null. If name cannot be null at all for Employee, then don’t use above method as it will ignore null names in this case.
2. Use Optional
Java 8 has introduced a new class called Optional.In general, we do not find any value in method, we return null from it and it becomes pain for caller to check for null to use it.
For example:
|
public static Employee findEmployee(List<Employee employeeList,String name) { for(Employee e:employeeList) { if(e.getName().equalsIgnoreCase(name)) { return e; } } return null; } |
As you can see, if we did not find employee in employeeList, we are returning null from findEmployee() method. The caller will get employee object from findEmployee() method and may call getName() method which will in turn raise NullPointerException.You can use Optional to avoid such situations.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class JavaOptionalMain { public static void main(String[] args) { List<Employee> employeeList = createEmployeeList(); Optional<Employee> employeeOpt = findEmployee(employeeList,«John»); if(employeeOpt.isPresent()) { Employee employee = employeeOpt.get(); System.out.println(«Employee name: «+employee.getName()); } else { System.out.println(«There is no employee with name John»); } } public static Optional<Employee> findEmployee(List<Employee> employeeList,String name) { for(Employee e:employeeList) { if(e.getName().equalsIgnoreCase(name)) { return Optional.of(e); } } return Optional.empty(); } public static List<Employee> createEmployeeList() { List<Employee> employeeList=new ArrayList<>(); Employee e1=new Employee(«Adam»,23); Employee e2=new Employee(«Dave»,34); Employee e3=new Employee(«Carl»,45); Employee e4=new Employee(«Mohan»,29); Employee e5=new Employee(«Paresh»,30); employeeList.add(e1); employeeList.add(e2); employeeList.add(e3); employeeList.add(e4); employeeList.add(e5); return employeeList; } } |
There is no employee with name John
It gives indication to caller than returned value can be null.
3. Use ternary opertor
You can use ternary operation to check for null.
|
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { Employee e1=null; String name = e1==null?e1.getName():«»; System.out.println(«Employee Name: «+ name); } } |
As you can see, we won’t get NullPointerException here.
4. Keep check on arguments of method
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog; public class InvokingMethodOnNullMain { public static void main(String[] args) { String str=null; int len=getLength(str); System.out.println(«Length of String:»+ len); } public static int getLength(String str) { if(str!=null) { return str.length(); } else { return 0; } } } |
5. Use StringUtils from Apache Common
You can use StringUtils class to take care of lots of String null and empty String check. Sometimes you need to check if String is null or empty, you can use isEmpty method from StringUtils to take care of it.
That’s all about Exception in thread «main» java.lang.NullPointerException in java.
In this post, we provide 3 fixes For The “exception in thread “main” java.lang.nullpointerexception” error.
As you can see, over on Twitter lots of people experience this frustrating error:
Exception in thread «main» java.lang.NullPointerException
[error] at org.apache.spark.rdd.RDD.<init>(RDD.scala:79)Today’s a bad day :/
— Mario Pastorelli (@mapastr) December 1, 2015
JVM: Exception in thread «main» java.lang.NullPointerException
ME: Ah, no— i stan birds 🎵🎷🐓 (@_ardeej) November 7, 2015
cat ~/.bash_aliases
alias java = echo «Exception in thread «main» java.lang.NullPointerException.»— Жизнь Убогая (@grepdev) February 4, 2016
The exception in thread “main”java.lang.nullpointerexception error is probably the first exception you will encounter when using java. It is challenging to solve since the name has a pointer, yet Java does not support pointers such as multiple inheritances.
In this article, we include a comprehensive guide on what the error is and how you can fix it. In Java, a null value is allocated to an object as reference. It shows that the object is pointing to a piece of data that is unknown.
Any NullPointerExceptions error means that you are pointing to something non-existent. For instance, it is like searching for a 5th spot when there are only four spots. It comes about when you fail to fill your array of types. Therefore, it happens when the reference does not point to any location.
Failing to provide value to every index of your array will cause java to assign the array with default values. Java will give each array a default value – null. That is how a nullPointerExceptions comes about since Java does not allow null.
While it is a real nightmare for beginners, it is an error that is quite easy to solve. Before discussing various ways to address the error, it is essential to understand what it is, why the error comes about, and how to avoid it.
Quick Video Fix
The exception in thread “main”java.lang.nullpointerexception error is an error or an exception which comes about when you try to conduct an operation with an object that has a null value. The “main” part means that the exception is in the main thread.
Since it is a runtime exception, don’t expect to find a NullPointerException in a program. Being a runtime exception implies that the program ends at the runtime instead of at the compile time.
The error occurs when:
- You call on an instance method on any null object
- Calling the length of an array if the array is null
- You access or change any variable on a null object
- You throw a null when an exception is expecting to throw
- Changing or accessing slots of null similar to an array
- Trying to synchronize a null object or when you use null in a synchronized java block
Like we have mentioned earlier, null is a unique value that Java uses. It is essential when coding using some design patterns such as the Singleton pattern or Null Object pattern. That is why we need a null value.
A null object pattern acts as a surrogate for a missing object in a particular type; while the singleton pattern makes sure an instance of a class is created once. For example, declaring constructors to be private, and later forming a public method which returns a unique example of the entire type.
How to Fix the Exception in thread main java.lang.nullpointerexception java Error
To successfully solve a NullPointerException error in Java, you first need to identify the cause. It is quite easy to know the cause of the error. Just check the stack-trace of the exception. The stack-case will show you the exact line where the NPE has occurred.
Now, go to the line with the error and check for possible object operations. For instance, check an accessing field, throwing an exception, or calling methods. These will give you a hint on the null object.
After identifying the null object, we are halfway done. Understand why the object is invalid, and use the fixes below to solve the exception. Note that the second part of identifying the error may vary. The null may be from a factory or a thread.
Since there are different causes of the thread “main”java.lang.nullpointerexception, we cannot narrow down to one solution. However, these different fixes will help you avoid the error:
1st Fix: Hash Tables
Check your coding practice. If you are coding using a “Hash Table” class, a user from DevShed forums recommends the following:
- Instead of using HashTable, it’s better to use HashMap since the former is really old.
- Use a file with “Properties file format.”
Video Overview: Data Structures: Hash Tables
2nd Fix: Cryptography Extension Update
According to Symantec, if you encounter the problem when trying to run Java LiveUpdate ConfigEditor, it could be that the JCE- Java Cryptography Extension files need to be updated, or that the LiveUpdate Configuration file is unreadable. You can fix this by following these steps:
- Update your JCE policy files
- Delete LiveUpdate.conf files then create a new one
- Alternatively, you can also correct the Java Path
Note that this fix is only applicable to Windows 2003 and 2008.
Video Overview: Java Cryptography Architecture (JCA)
3rd Fix: Argument Method
Java Code Geeks recommend checking the argument of a method. Before performing the body of a method, it is essential to check the argument of the process for any null values. Only proceed with the execution after making sure there aren’t any null values.
Alternatively, you can send an “IllegalArguementException” and let the calling method know that something is wrong with previously passed arguments.
For instance:
public static int getLength(String s) {
if (s == null)
throw new IllegalArguementException (“The argument cannot be null”);
return s. length ( ) ;
}
Forum Feedback
To find more about the Exception in thread “main” java.lang.NullPointerException error and what troubles people have with it, we search through Java boards and forums. In general, users were interested in Exception in thread “main” java.lang.NullPointerException in Java, Selenium Eclipse, and Glassfish. They also wanted to know about Exception in thread main java.lang.NullPointrException at java.io.file. init (unknown source).
A computer user shared that he had been stuck for hours trying to solve the error message “Exception in thread “main” java.lang.NullPointerException” and that he was at his wit’s ends. He asked fellow JavaScript forum member for advice, and they said that he had made a common JavaScript mistake. They explained that he had a variable with a null value somewhere in his code and as a result, his method was throwing the NullPointerException.
Another forum poster remarks that you should learn to read your stack trace if you want to be able to find and fix your code mistakes. He points out that after Exception in thread “main” java.lang.NullPointerException, you will see java: (line number), which indicates in which line you should look for the error. Then you should go over that line and find the variable, which is null and fix it in the code.
A poster explains that NullPointerException occurs when you declare an object reference, but do not create the object. For example, if you create an array of a list, it doesn’t create the objects in the list. In other words, when you get NullPointerException, you’re trying to point something to something that has a null value and therefore, doesn’t exist. The individual reminds that you can’t call a method on null in JavaScript and that it’s important not to code around the error.
A person stated that if you have problems with NullPointerException you might want to start checking whether your variables are null before calling them.
- He mentioned that you could use @Nullable and @NotNull annotations.
- The user explains that @Nullable remind you that you have to check for NullPointerExpceptions when you call a method that could return a null value and when you’re differencing values that could be null. On the other hand, @NotNull declares that a method shouldn’t be null and that a variable cannot have a null value.
- The user pointed out that you have to think about two phases if you want to use an object.
- First, you have to declare it, and then you have to initialize it.
- If you do not initialize an object, then you’ll get the error Exception in thread “main” java.lang.NullPointerException.
- The poster recommends that when you’re in doubt to use print to see what’s inside your variable.
A forum user shared that the code he had written was throwing the error Exception in thread “main” java.lang.NullPointerException.
- He had checked his variable, and it wasn’t null, so he wasn’t sure how to proceed.
- When he got in touch with other JavaScript users, they pointed out that he had a problem with his manager array because he had forgotten to set one element in the array.
- As a result, one of his elements was null, which was triggering the NullPointerException.
Another Java expert says that in Java you don’t work with an array of objects. Instead, you deal with arrays of references to objects, and that’s why your references must point to an object before you call a method.
- He explains that NullPointerException is a Runtime Exception, a programmatic error. The poster points out that you can assign a null value to a reference, but you can’t use such a reference.
- He also remarks that you might get the NullPointerException if you’re trying to access or modify a variable with a null value.
A person observed that dealing with Null Pointers is easier if you use Java 8 or above because you can use Optional. It’s a new class in Java, which encapsulated an optional value and helps you avoid NullPointerExceptions altogether. On the other hand, some Java users are against using the Optional class because it doesn’t make your code more correct and they advise that you rely on the regular methods in Java to check for a null value.
A person also comments that you’ll get Exception in thread “main” java.lang.NullPointerException if you’re attempting to throw null as if it were a Throwable value or when you try to access/modify slots of nulls as if you’re trying to access/modify an array.
Conclusion
Remember that any NullPointerException comes about when you use a method on a variable which has not been initialized. Therefore, you can avoid the error by always setting a default value for every variable.
Other ways to avoid exception in thread main java.lang.nullpointerexception include using String.valueOf () method as opposed to toString () method. For instance, if an application code needs a string representation, use the static method instead of the toString method which throws an NPE.
Consider using the ternary operator which is in the form of Boolean expression seven value1: value2. Alternatively, you can avoid the error by creating methods which return to an empty collection, rather than those which return to null. Lastly, use Apache`s StringUtils class. Apache is a library which provides utilities for APU; for example, string manipulation methods.
Now that we have discussed what the error is, how it comes about, remedies to fix, and how to avoid it, you are in a better position to enjoy coding using Java.
Ryan is a computer enthusiast who has a knack for fixing difficult and technical software problems. Whether you’re having issues with Windows, Safari, Chrome or even an HP printer, Ryan helps out by figuring out easy solutions to common error codes.
Довольно часто при разработке на 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 и как эффективно предотвращать такие ситуации при разработке программ.








