Sunday 15 February 2015

java - What is a Null Pointer Exception, and how do I fix it? -



java - What is a Null Pointer Exception, 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 programme terminate prematurely?

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

int x; x = 10;

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

but, when seek declare reference type different happens. take next 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 sec 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 effort dereference num before creating object nullpointerexception. in trivial cases compiler grab problem , allow know "num may not have been initialized" sometime write code not straight create object.

for instance may have method follows:

public void dosomething(integer num){ //do num }

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

dosomething(null);

in case num null. best way avoid type of exception check null when did not create object yourself. dosomething should re-written as:

public void dosomething(integer num){ if(num != null){ //do num } }

finally, how pinpoint exception location & cause using stack trace

java nullpointerexception

No comments:

Post a Comment