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


what null pointer exceptions (java.lang.nullpointerexception) , causes them?

what methods/tools can used determine cause stop exception causing program terminate prematurely?

when declare reference variable (i.e. object) creating pointer object. consider following code declare variable of primitive type int:

int x; x = 10; 

in example variable x int , java initialize 0 you. when assign 10 in second line value 10 written memory location pointed x.

but, when try declare reference type different happens. take following code:

integer num; num = new integer(10); 

the first line declares variable named num, but, not contain primitive value. instead contains pointer (because type integer reference type). since did not yet point java sets null, meaning "i pointing @ nothing".

in second line, new keyword used instantiate (or create) object of type integer , pointer variable num assigned object. can reference object using dereferencing operator . (a dot).

the exception asked occurs when declare variable did not create object. if attempt dereference num before creating object nullpointerexception. in trivial cases compiler catch problem , let know "num may not have been initialized" write code not directly create object.

for instance may have method follows:

public void dosomething(someobject obj){    //do obj } 

in case not creating object obj, rather assuming created before dosomething method called. unfortunately possible call method this:

dosomething(null); 

in case obj null. if method intended passed-in object, appropriate throw nullpointerexception because it's programmer error , programmer need information debugging purposes.

alternatively, there may cases purpose of method not solely operate on passed in object, , therefore null parameter may acceptable. in case, need check null parameter , behave differently. should explain in documentation. example, dosomething written as:

/**   * @param obj optional foo ____. may null, in case    *  result ____. */ public void dosomething(someobject obj){     if(obj != null){        //do     } else {        //do else     } } 

finally, how pinpoint exception location & cause using stack trace


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -