Ошибка джава лэнг

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

Решение ошибки

java.lang.nullpointerexception

Причин у этой ошибки как правило две: некорректно работающая программа и проблемы с работой пакета Java, который установлен на компьютере пользователя. Чтобы устранить ошибку java.lang.nullpointerexception, выполняют следующие несколько шагов:

  • Попробуйте переустановить Java-пакет, установленный в вашей операционной системе. Зайдите в «Программы и компоненты» и удалите установленный пакет. Затем перейдите по этой ссылке на официальный сайт, загрузите последнюю версию Java и установите ее.
  • Помимо прочего, сама запускаемая программа может быть источником проблемы. Возможно, что-то не так пошло во время установочного процесса, вследствие чего были повреждены файлы программы. В общем, переустановите и посмотрите на результат.
  • Если вы пытаетесь запустить у себя на компьютере Minecraft и сталкивайтесь с ошибкой, то многим пользователям помогло создание в системе новой Администраторской учетной записи, а затем запуск игры от имени Администратора(звучит сложнее, чем кажется).
  • Если вы можете связаться с разработчиками запускаемой программы – сделайте это и объясните им ситуацию с ошибкой java.lang.nullpointerexception.

Обычно, вышеуказанные решения помогают большинству пользователей избавиться от ошибки java.lang.nullpointerexception. Мы надеемся, что и они вам помогли.

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

Ошибка java.lang.nullpointerexception

Содержание

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Заключение

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

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

public class NullPointerExcept {

public static void main(String[] args) {

String s = «abcd»;

foo(null);

bar(null);

}

// Using a try-catch block:

static void foo(String x){

try {

System.out.println(«First character: » + x.charAt(0));

}

catch(NullPointerException e) {

System.out.println(«NullPointerException thrown!»);

}

}

// Using if-else condition:

static void bar(String x){

if(x != null)

System.out.println(«First character: » + x.charAt(0));

else

System.out.println(«NullPointerException thrown!»);

}

}

Hey Geeks, today we will see what NullPointerException means and how we can fix it in Android Studio. To understand NullPointerException, we have to understand the meaning of Null.

What is null?

“null” is a very familiar keyword among all the programmers out there. It is basically a Literal for Reference datatypes or variables like Arrays, Classes, Interfaces, and Enums. Every primitive data type has a default value set to it(Ex: True and False value for Boolean). Similarly, Reference Datatype Variables have Null value as default if it is not initialized during declaration.

Java

import java.util.Scanner;

public class Main

{

    public static void main(String[] args) {

        Scanner sc = null;

        System.out.println(sc);

    }

}

Output: 

null

It is also important to note that we cannot directly store a null value in a primitive variable or object as shown below.

Java

import java.util.Scanner;

public class Main

{

    public static void main(String[] args) {

        int i = null;

        System.out.println(i);

    }

}

Output:

Main.java:5: error: incompatible types:  cannot be converted to int
        int i = null;
                ^
1 error

What is NullPointerException?

It is a run-time exception that arises when an application or a program tries to access the object reference(accessing methods) which has a null value stored in it. The null value gets stored automatically in the reference variable when we don’t initialize it after declaring as shown below.  

Java

import java.util.Scanner;

public class Main

{

    public static void main(String[] args) {

        Scanner sc = null;

         int input =sc.nextInt();

         System.out.println(input);

    }

}

 Output:

Exception in thread "main" java.lang.NullPointerException                                                                                      
        at Main.main(Main.java:6)  

Null Pointer Exception in Android Studio

NullPointerException in Android Studio highlighted in yellow color in the below screenshot 

As you can observe from the above picture, it contains a Textview which is initialized to null. 

TextView textview = null;

The TextView reference variable(i.e. textview) is accessed which gives a NullPointerException.

textview.setText("Hello world");

The App keeps stopping abruptly

Code

Java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        TextView textview = null;

        textview.setText("Hello World");

    }

}

Handling the NullPointerException in Android Studio

To Handle the NullPointerException smoothly without making the app crash, we use the “Try – Catch Block” in Android.

  • Try: The Try block executes a piece of code that is likely to crash or a place where the exception occurs.
  • Catch: The Catch block will handle the exception that occurred in the Try block smoothly(showing a toast msg on screen) without letting the app crash abruptly.

The structure of Try -Catch Block is shown below

Code

Java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        TextView textview = null;

        try {

            textview.setText("Hello world");

        }

        catch(Exception e){

            Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();

        }

    }

}

Output:

Using Try Catch we can catch the exception on the screen

How to fix the NullPointerException?

To avoid NullPointerException we have to initialize the Textview component with the help of findviewbyid( ) method as shown below. The findViewbyId( ) takes the “id” value of the component as the parameter. This method helps locate the component present in the app. 

Solving the NullPointerException 

TextView with id textview

Code

Java

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.TextView;

import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        TextView textview = findViewById(R.id.textview);

        try {

            textview.setText("Hello world");

        }

        catch(Exception e){

            Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();

        }

    }

}

Output:

Output after Solving NullPointerException

As you can see after initializing the text view component we have solved the NullPointerException. Hence in this way, we can get rid of NullPointerException in Android Studio.

Last Updated :
25 Jul, 2022

Like Article

Save Article

Понравилась статья? Поделить с друзьями:
  • Ошибка датчика детонации ваз 2115
  • Ошибка дескриптора usb устройства windows 10 принтер
  • Ошибка датчика adc 092 651 xerox
  • Ошибка двигателя машина троит
  • Ошибка датчик абсолютного давления газель