NullPointerException occurs because the program is trying to access a method or a field on null. Now what is a null, although the explanation of null may go beyond the scope of this blog but for the topic purpose we may say that any object which does not contain any memory reference is null. Object doesn't have any memory reference-the cause of this may be:
1] Object not initialised using the new operator.
2] Object may somewhere in the program have been assigned a null.
3] An unitialised array being subscripted, i.e. indexed.
For e.g.
Example for 1st cause:
A1] String str=null;
A2] str.equals("somestring");----------->here you will get NullPointerException because str has not been initialised
Example for 2nd cause:
B1] String str=new String("somestring");
B2] String str1=null;
B3] str=str1;
B4] str.equals("somestring");------------->here you will get NullPointerException because str no more contains any object reference though it was initialised to one(B1),it is assigned what is contained in str1(B3) and str1 is null(B2)
Example for 3rd cause:
C1] String str[]=new String[3];
C2] str=null;
C3] str[0]="somestring";---------------->here you will get NullPointerException because str is an array of strings which is not yet initialised and hence there is no memory for any of the elements and we are trying to assign a string to such an element of the string.
Quote
Only he who has seen all the failure will get all the success.
Subscribe to:
Post Comments (Atom)
2 comments:
This is nice set of information with examples and I am glad to post first comment in your blog ;-)
Keep posting useful information and Keep up the Good Work !!!!
Hi Uday
Can u tell me difference between interface and abstract class with example?
Post a Comment