Sunday, 15 January 2012

java - What is a NullPointerException, and how do I fix it? -


What are the null pointer exceptions ( java.lang.NullPointerException ) and what is the reason for them?

Which method / tool can be used to determine the reason so that you stop the exception due to terminating the program prematurely?

When you declare a reference variable (i.e. one object), then you can actually declare an object Make an indicator. Consider the following code where you declare a variable of the primitive type int :

  int x; X = 10;  

In this example, the variable x is a int and Java will start it in 0 for you. When you give it for 10 in the second row, your value is written in 10 memory place, which is indicated by x.

However, when you try to declare a different type of reference type, take the following code:

  integer number; Num = new integer (10);  

declares a variable called the first line, but does not have a primitive value. Instead it has an indicator (because this type is the integer which is the reference type). Since you have not said so far, what does it tap to indicate Java, which means "I'm not saying anything".

In the second line, the keyword new is used to instantiate the integer type of object (or create) and the pointer variable number is assigned to this object . Now you dereferencing operator . You can refer to the object using (a point).

The exception that you asked is when you declare a variable but do not create an object if you try to dereference num If you do, you can obtain NullPointerException before receiving the item. The compiler will catch the problem in the most trivial cases and you have to tell that "the number has not been started", but sometimes you write a code that does not make the object directly. For example, the method is as follows:

  do something for public void doSomething (SomeObject obj) {// obj}  

that status Unfortunately, it is possible to call the method in this way: obj , rather assuming that it was created before the doSomething method: < / P>

  doSomething (empty);  

In that case, obj is zero if the purpose of the method is to do something in the object, then it is advisable to throw NullPointerException This is a programmer error and the programmer will need that information for debugging purposes.

Alternatively, there may be cases where the purpose of the method is not fully operated to pass in the object, and therefore a null parameter may be acceptable. In this case, you will need to examine a null parameter and behave differently. You should also understand this in the document. For example, doSomething can be written as:

  / ** * @ an alternative foo for the ultimate obj ____. False, in that case * the result will be ____.  

Finally

/ div>

No comments:

Post a Comment