NullPointerException nedir ve bunu nasıl düzeltirim?

Oct 20 2008

Boş İşaretçi İstisnaları ( java.lang.NullPointerException) nedir ve bunlara ne sebep olur?

Nedeni belirlemek için hangi yöntemler / araçlar kullanılabilir, böylece istisnanın programın zamanından önce sonlanmasına neden olmasını önleyebilirsiniz?

Yanıtlar

3848 VincentRamdhanie Oct 20 2008 at 20:54

Bir referans değişkeni (yani bir nesne) bildirdiğinizde, gerçekten bir nesneye işaretçi oluşturursunuz. İlkel türde bir değişken bildirdiğiniz aşağıdaki kodu göz önünde bulundurun int:

int x;
x = 10;

Bu örnekte, değişken xbir olduğunu intve Java bunu başlatacaktır 0senin için. 10İkinci satırdaki değerini atadığınızda, değeriniz 10tarafından atıfta bulunulan hafıza konumuna yazılır x.

Ancak bir referans türü belirtmeye çalıştığınızda farklı bir şey olur. Aşağıdaki kodu alın:

Integer num;
num = new Integer(10);

İlk satır, adlandırılmış bir değişkeni bildirir num, ancak aslında henüz ilkel bir değer içermemektedir. Bunun yerine, bir işaretçi içerir (çünkü tür Integer, bir başvuru türüdür). Henüz neye işaret edeceğinizi söylemediğiniz için, Java null, " Ben hiçbir şeye işaret etmiyorum " anlamına gelir .

İkinci satırda, newanahtar kelime türü bir nesneyi somutlaştırmak (veya oluşturmak) için kullanılır Integerve işaretçi değişkeni numbu Integernesneye atanır .

NullPointerExceptionBir değişkeni bildirir ancak bir nesne oluşturmak ve değişken (denilen içeriğini kullanmayı denemeden önce değişkene atamak vermedi oluşur başvurusu kaldırma ). Yani aslında var olmayan bir şeye işaret ediyorsunuz.

Referans dışı bırakma genellikle .bir yönteme veya alana erişmek için kullanıldığında veya [bir diziyi indekslemek için kullanıldığında gerçekleşir .

numNesneyi oluşturmadan ÖNCE referansı kaldırmaya çalışırsanız, bir NullPointerException. En önemsiz durumlarda, derleyici sorunu yakalar ve size bunu "" bildirir num may not have been initialized, ancak bazen nesneyi doğrudan oluşturmayan bir kod yazabilirsiniz.

Örneğin, aşağıdaki gibi bir yönteminiz olabilir:

public void doSomething(SomeObject obj) {
   //do something to obj, assumes obj is not null
   obj.myMethod();
}

Bu durumda, nesneyi objdeğil, doSomething()yöntem çağrılmadan önce oluşturulduğunu varsayarsınız . Not, yöntemi şu şekilde çağırmak mümkündür:

doSomething(null);

Bu durumda, objis nullve ifade obj.myMethod()bir NullPointerException.

Yöntemin, yukarıdaki yöntemin yaptığı gibi, iletilen nesneye bir şey yapması amaçlanıyorsa, NullPointerExceptionbir programcı hatası olduğundan ve programcı bu bilgilere hata ayıklama amacıyla ihtiyaç duyacağı için atılması uygundur .

Ek olarak NullPointerExceptionyöntemin mantığının bir sonucu olarak atılan s, ayrıca yöntemi argümanlar kontrol edebilirsiniz nullaçıkça bir yöntemin başına yakın aşağıdaki gibi bir şey ekleyerek değerler ve atmak NPES:

//Throws an NPE with a custom error message if obj is null
Objects.requireNonNull(obj, "obj must not be null");

Hata mesajınızda hangi nesnenin olamayacağını açıkça söylemenin faydalı olacağını unutmayın null. Bunun gibi doğrulama yapmanın avantajı, 1) kendi daha net hata mesajlarınızı döndürebilmeniz ve 2) bildiğiniz yöntemin geri kalanı için obj, yeniden atanmadıkça boş olmadığını ve güvenli bir şekilde referans alınabileceğini bilmenizdir .

Alternatif olarak, yöntemin amacının yalnızca aktarılan nesne üzerinde işlem yapmak olmadığı durumlar olabilir ve bu nedenle boş bir parametre kabul edilebilir. Bu durumda, boş bir parametre olup olmadığını kontrol etmeniz ve farklı davranmanız gerekir. Bunu dokümantasyonda da açıklamalısınız. Örneğin doSomething()şu şekilde yazılabilir:

/**
  * @param obj An optional foo for ____. May be null, in which case 
  *  the result will be ____.
  */
public void doSomething(SomeObject obj) {
    if(obj == null) {
       //do something
    } else {
       //do something else
    }
}

Son olarak, Stack Trace kullanarak istisna ve neden nasıl belirlenir?

Nedeni belirlemek için hangi yöntemler / araçlar kullanılabilir, böylece istisnanın programın zamanından önce sonlanmasına neden olmasını önleyebilirsiniz?

Bulma hatalarına sahip sonar, NPE'yi algılayabilir. Sonar, JVM Dinamik olarak neden olan boş işaretçi istisnalarını yakalayabilir mi?

Şimdi Java 14, NullPointerException'ın temel nedenini göstermek için yeni bir dil özelliği ekledi. Bu dil özelliği, 2006'dan beri SAP ticari JVM'nin bir parçasıdır. Aşağıdakiler, bu şaşırtıcı dil özelliğini anlamak için 2 dakika okundu.

https://jfeatures.com/blog/NullPointerException

Java 14'te aşağıdaki örnek NullPointerException Exception mesajı verilmiştir:

"main" iş parçacığında java.lang.NullPointerException: "java.util.List.size ()" çağrılamıyor çünkü "list" boş

898 BilltheLizard Oct 20 2008 at 20:20

NullPointerExceptions, bir nesneye başvuruyormuş gibi bellekte hiçbir konuma (null) işaret eden bir başvuruyu kullanmaya çalıştığınızda oluşan istisnalardır. Boş bir başvuruda bir yöntemi çağırmak veya boş bir başvurunun bir alanına erişmeye çalışmak bir NullPointerException. Bunlar en yaygın olanlardır, ancak diğer yollar NullPointerExceptionjavadoc sayfasında listelenmiştir .

Muhtemelen a'yı göstermek için bulabileceğim en hızlı örnek kod şöyle NullPointerExceptionolurdu:

public class Example {

    public static void main(String[] args) {
        Object obj = null;
        obj.hashCode();
    }

}

İçerideki ilk satırda main, Objectreferansı açıkça objeşit olarak ayarlıyorum null. Bu, bir referansım olduğu anlamına gelir, ancak herhangi bir nesneye işaret etmiyor. Bundan sonra, referansı, üzerinde bir yöntem çağırarak bir nesneyi işaret ediyormuş gibi ele almaya çalışıyorum. Bu NullPointerException, referansın işaret ettiği konumda yürütülecek kod bulunmadığından sonuçlanır .

(Bu bir tekniktir, ancak şunu belirtmeyi gerektirdiğini düşünüyorum: Null'a işaret eden bir referans, geçersiz bir bellek konumuna işaret eden bir C işaretçisiyle aynı değildir. Boş bir işaretçi, kelimenin tam anlamıyla hiçbir yere işaret etmez , bu da biraz farklıdır geçersiz olan bir konuma işaret ediyor.)

709 fgb Jun 08 2014 at 02:22

NullPointerException nedir?

JavaDocs , başlamak için iyi bir yerdir . Bunları kapsıyorlar:

Bir nesnenin gerekli olduğu bir durumda bir uygulama null kullanmaya çalıştığında atılır. Bunlar şunları içerir:

  • Boş bir nesnenin örnek yöntemini çağırma.
  • Boş bir nesnenin alanına erişim veya değiştirme.
  • Boş değerin uzunluğunu bir diziymiş gibi almak.
  • Null alanlarına bir diziymiş gibi erişme veya değiştirme.
  • Atılabilir bir değermiş gibi boş atma.

Uygulamalar, boş nesnenin diğer yasa dışı kullanımlarını belirtmek için bu sınıfın örneklerini atmalıdır.

Ayrıca bir null başvuru kullanmaya kalkarsanız Eğer durum synchronizedda, bu istisna durumu, JLS başına :

SynchronizedStatement:
    synchronized ( Expression ) Block
  • Aksi takdirde, İfadenin değeri null ise, a NullPointerExceptionatılır.

Nasıl düzeltirim?

Yani bir NullPointerException. Nasıl tamir edersin? Aşağıdakileri yapan basit bir örnek alalım NullPointerException:

public class Printer {
    private String name;

    public void setName(String name) {
        this.name = name;
    }

    public void print() {
        printString(name);
    }

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");
    }

    public static void main(String[] args) {
        Printer printer = new Printer();
        printer.print();
    }
}

Boş değerleri tanımlayın

İlk adım, istisnaya hangi değerlerin neden olduğunu tam olarak belirlemektir . Bunun için biraz hata ayıklama yapmamız gerekiyor. Bir yığın izini okumayı öğrenmek önemlidir . Bu size istisnanın nereye atıldığını gösterecektir:

Exception in thread "main" java.lang.NullPointerException
    at Printer.printString(Printer.java:13)
    at Printer.print(Printer.java:9)
    at Printer.main(Printer.java:19)

Burada istisnanın 13. satıra ( printStringyöntemde) atıldığını görüyoruz . Satıra bakın ve günlük kaydı ifadeleri ekleyerek veya bir hata ayıklayıcı kullanarak hangi değerlerin boş olduğunu kontrol edin . Bunun sboş olduğunu anlarız ve bu lengthyöntemin çağrılması istisnayı atar. s.length()Yöntemden çıkarıldığında programın istisna atmayı bıraktığını görebiliriz.

Trace where these values come from

Next check where this value comes from. By following the callers of the method, we see that s is passed in with printString(name) in the print() method, and this.name is null.

Trace where these values should be set

Where is this.name set? In the setName(String) method. With some more debugging, we can see that this method isn't called at all. If the method was called, make sure to check the order that these methods are called, and the set method isn't called after the print method.

This is enough to give us a solution: add a call to printer.setName() before calling printer.print().

Other fixes

The variable can have a default value (and setName can prevent it being set to null):

private String name = "";

Either the print or printString method can check for null, for example:

printString((name == null) ? "" : name);

Or you can design the class so that name always has a non-null value:

public class Printer {
    private final String name;

    public Printer(String name) {
        this.name = Objects.requireNonNull(name);
    }

    public void print() {
        printString(name);
    }

    private void printString(String s) {
        System.out.println(s + " (" + s.length() + ")");
    }

    public static void main(String[] args) {
        Printer printer = new Printer("123");
        printer.print();
    }
}

See also:

  • Avoiding “!= null” statements in Java?

I still can't find the problem

If you tried to debug the problem and still don't have a solution, you can post a question for more help, but make sure to include what you've tried so far. At a minimum, include the stacktrace in the question, and mark the important line numbers in the code. Also, try simplifying the code first (see SSCCE).

516 StephenC Jun 22 2014 at 09:16

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.

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.

432 RakeshBurbure Oct 20 2008 at 20:21

It's like you are trying to access an object which is null. Consider below example:

TypeA objA;

At this time you have just declared this object but not initialized or instantiated. And whenever you try to access any property or method in it, it will throw NullPointerException which makes sense.

See this below example as well:

String a = null;
System.out.println(a.toString()); // NullPointerException will be thrown
365 nathan1138 Apr 17 2013 at 09:57

A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling 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.

Applications should throw instances of this class to indicate other illegal uses of the null object.

Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html

341 MrZebra Oct 20 2008 at 20:25

A null pointer is one that points to nowhere. When you dereference a pointer p, you say "give me the data at the location stored in "p". When p is a null pointer, the location stored in p is nowhere, you're saying "give me the data at the location 'nowhere'". Obviously, it can't do this, so it throws a null pointer exception.

In general, it's because something hasn't been initialized properly.

329 L.G. Jun 25 2014 at 18:17

A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerExceptions at all.

See also: A good list of best practices

I would add, very important, make a good use of the final modifier. Using the "final" modifier whenever applicable in Java

Summary:

  1. Use the final modifier to enforce good initialization.
  2. Avoid returning null in methods, for example returning empty collections when applicable.
  3. Use annotations @NotNull and @Nullable
  4. Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
  5. Use equals with a known object first: if("knownObject".equals(unknownObject)
  6. Prefer valueOf() over toString().
  7. Use null safe StringUtils methods StringUtils.isEmpty(null).
  8. Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.
323 ashishbhatt Jan 28 2012 at 13:45

In Java, everything (excluding primitive types) is in the form of a class.

If you want to use any object then you have two phases:

  1. Declare
  2. Initialization

Example:

  • Declaration: Object object;
  • Initialization: object = new Object();

Same for the array concept:

  • Declaration: Item item[] = new Item[5];
  • Initialization: item[0] = new Item();

If you are not giving the initialization section then the NullPointerException arise.

322 javidpiprani Sep 24 2013 at 13:01

A null pointer exception is an indicator that you are using an object without initializing it.

For example, below is a student class which will use it in our code.

public class Student {

    private int id;

    public int getId() {
        return this.id;
    }

    public setId(int newId) {
        this.id = newId;
    }
}

The below code gives you a null pointer exception.

public class School {

    Student student;

    public School() {
        try {
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

Because you are using student, but you forgot to initialize it like in the correct code shown below:

public class School {

    Student student;

    public School() {
        try {
            student = new Student();
            student.setId(12);
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}
315 OscarRyz Oct 21 2008 at 03:05

In Java all the variables you declare are actually "references" to the objects (or primitives) and not the objects themselves.

When you attempt to execute one object method, the reference asks the living object to execute that method. But if the reference is referencing NULL (nothing, zero, void, nada) then there is no way the method gets executed. Then the runtime let you know this by throwing a NullPointerException.

Your reference is "pointing" to null, thus "Null -> Pointer".

The object lives in the VM memory space and the only way to access it is using this references. Take this example:

public class Some {
    private int id;
    public int getId(){
        return this.id;
    }
    public setId( int newId ) {
        this.id = newId;
    }
}

And on another place in your code:

Some reference = new Some();    // Point to a new object of type Some()
Some otherReference = null;     // Initiallly this points to NULL

reference.setId( 1 );           // Execute setId method, now private var id is 1

System.out.println( reference.getId() ); // Prints 1 to the console

otherReference = reference      // Now they both point to the only object.

reference = null;               // "reference" now point to null.

// But "otherReference" still point to the "real" object so this print 1 too...
System.out.println( otherReference.getId() );

// Guess what will happen
System.out.println( reference.getId() ); // :S Throws NullPointerException because "reference" is pointing to NULL remember...

This an important thing to know - when there are no more references to an object (in the example above when reference and otherReference both point to null) then the object is "unreachable". There is no way we can work with it, so this object is ready to be garbage collected, and at some point, the VM will free the memory used by this object and will allocate another.

287 Makoto May 25 2014 at 13:11

Another occurrence of a NullPointerException occurs when one declares an object array, then immediately tries to dereference elements inside of it.

String[] phrases = new String[10];
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}

This particular NPE can be avoided if the comparison order is reversed; namely, use .equals on a guaranteed non-null object.

All elements inside of an array are initialized to their common initial value; for any type of object array, that means that all elements are null.

You must initialize the elements in the array before accessing or dereferencing them.

String[] phrases = new String[] {"The bird", "A bird", "My bird", "Bird"};
String keyPhrase = "Bird";
for(String phrase : phrases) {
    System.out.println(phrase.equals(keyPhrase));
}